The Node.js HTTP Server
object provides the fundamental framework to implement HTTP servers. It provides an underlying socket that listens on a port and handles receiving requests and then sending responses out to client connections. While the server is listening, the Node.js application does not end.
The Server
object implements EventEmitter
and emits the events listed in Table 7.8. As you implement an HTTP server, you need to handle at least some or all of these events. For example, at a minimum, you need an event handler to handle the request
event that is triggered when a client request is received.
To start the HTTP server, you need to first create a Server
object, using the createServer()
method, shown below:
http.createServer([requestListener])
This method returns the Server
object. The optional requestListener
parameter is a callback that is executed when the request event is triggered. The callback should accept two parameters. The first is an IncomingMessage
object representing the client request, and the second is a ServerResponse
object you use to formulate and send the response.
Once you have created the Server
object, you can begin listening on it by calling the listen()
method on the Server
object:
listen(port, [hostname], [backlog], [callback])
This is the method you are most likely to use. The following are the parameters:
port: Specifies the port to listen on.
hostname: Specifies when hostname
will accept connections; if omitted, the server accepts connections directed to any IPv4 address (INADDR_ANY
).
backlog: Specifies the maximum number of pending connections that are allowed to be queued. The default is 511
.
callback: Specifies the callback handler to execute when the server has begun listening on the specified port.
The following code shows an example of starting an HTTP server and listening on port 8080. Notice that a request callback handler function is passed into the createServer()
method:
var http = require('http'),
http.createServer(function (req, res) {
<<handle the request and response here>>
}).listen(8080);
You can use two other methods to listen for connections through the file system. The first accepts a path
to a file to listen on, and the second accepts an already open file descriptor handle
:
listen(path, [callback])
listen(handle, [callback])
To stop the HTTP server from listening once it has started, use the following close()
method:
close([callback])