How to use the Server function from http

Find comprehensive JavaScript http.Server code examples handpicked from public code repositorys.

http.Server is a class in Node.js that provides an HTTP server instance.

34
35
36
37
38
39
40
41
42
43
        // copy from http.Server
        this.timeout = 2 * 60 * 1000;
        this.allowHalfOpen = false;
        this.httpAllowHalfOpen = false;
    } else
        http.Server.call(this, requestListener);
}
inherits(Server, https.Server);

Server.prototype.setTimeout = function (msecs, callback) {
fork icon842
star icon58
watch icon20

+ 3 other calls in file

263
264
265
266
267
268
269
270
271
272
}

if ('number' == typeof srv) {
  debug('creating http server and binding to %d', srv);
  var port = srv;
  srv = http.Server(function(req, res){
    res.writeHead(404);
    res.end();
  });
  srv.listen(port);
fork icon0
star icon0
watch icon1

How does http.Server work?

http.Server is a Node.js module that creates an HTTP server which listens for incoming requests on a specified port and, when a request is received, emits a 'request' event containing a http.IncomingMessage instance and a http.ServerResponse instance, which can be used to handle the request and send a response back to the client.

107
108
109
110
111
112
113
114
115
116
    return (onlyOneHttpServer = originalCreateServer(...args));
};

// now, we force the server to listen to a specific port and a binding address, regardless of what
// hammerhead server.listen(anything)
const originalListen = http.Server.prototype.listen;
http.Server.prototype.listen = function (_proxyPort) {
    if (dontListen) return;
    originalListen.call(this, port, bindingAddress);
};
fork icon0
star icon0
watch icon0

+ 5 other calls in file

879
880
881
882
883
884
885
886
887
888
889
890
 * Listen to requests on port 3001
 * ===================================
 */
const PORT = process.env.PORT || 3001;


const server = http.Server(app);


server.listen(PORT, () =>
  console.log("~~~ Tuning in to the waves of port " + PORT + " ~~~")
);
fork icon0
star icon0
watch icon0

Ai Example

1
2
3
4
5
6
7
8
9
10
11
const http = require("http");

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain");
  res.end("Hello World!");
});

server.listen(3000, () => {
  console.log("Server running at http://localhost:3000/");
});

This example creates an HTTP server that listens on port 3000 and responds with "Hello World!" to any incoming request.

28
29
30
31
32
33
34
35
36
37
  this.timeout = 2 * 60 * 1000;
}
inherits(Server, tls.Server);
exports.Server = Server;

Server.prototype.setTimeout = http.Server.prototype.setTimeout;

exports.createServer = function(opts, requestListener) {
  return new Server(opts, requestListener);
};
fork icon0
star icon0
watch icon4