marko-36
marko-36

Reputation: 1496

httpServer.listen() firing before http.createServer(). Why? How?

const http = require('http');
const hostname = 'localhost';
const port = 3000;

http.createServer((req, res) => {
  console.log(`http.createServer..`);
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
}).listen(port, hostname, () => {
  console.log(`Server listening at http://${hostname}:${port}/`);
});

"Server running at http://localhost:3000/" logged to console immediately after running the module.

"http.createServer.." logged to console on request to port 3000.

I would expect both console.logs to execute right away, in opposite order. In other words, for createServer() to run first, including the callback function and then to .listen().

What is happening here?

EDIT: Documentation says the function within .createServer() is not a callback, but a requestListener - a function which is automatically added to the 'request' event. So, how does this work?

Upvotes: 0

Views: 316

Answers (1)

Dishonered
Dishonered

Reputation: 8851

This is because the request listener function (which you pass to createServer) is executed only when a request event is emitted.

From the docs

The requestListener is a function which is automatically added to the 'request' event.

The request event

Emitted each time there is a request. Note that there may be multiple requests per connection (in the case of HTTP Keep-Alive connections).

Upvotes: 2

Related Questions