server.listen()

Starts the HTTP server listening for connections on a port or socket.

Since Node 0.x Spec ↗

Syntax

server.listen([port[, host]][, callback])

Parameters

NameTypeRequiredDescription
port number No The TCP port. `0` picks a random free port. Omit for a Unix socket via the `path` option.
host string No The interface to bind, e.g. `'127.0.0.1'` or `'0.0.0.0'`.
callback function No Invoked once the server is listening.

Returns

http.Server — The server, for chaining.

Examples

server.listen(3000, () => {
  console.log('listening on http://localhost:3000');
});
Output
listening on http://localhost:3000
server.listen(0, () => {
  console.log('random port:', server.address().port);
});
Output
random port: 54213

Notes

Listening is asynchronous; use the callback or the `'listening'` event before reporting readiness. Handle the `'error'` event for `EADDRINUSE`. Bind to `127.0.0.1` in development to avoid exposing the server on the network.

See also