-5

Can anyone explain which instruction is getting executed first. http.createServer() or server.listen and when callback function inside createserver will execute?

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

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

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
phuzi
  • 12,078
  • 3
  • 26
  • 50
  • 2
    Given `.listen()` is called on the return value of `createServer()`, there's only one possible order. Regarding when the callback is called, check the [documentation of the method](https://nodejs.org/api/http.html#httpcreateserveroptions-requestlistener). – Bergi Oct 25 '21 at 14:15
  • Surely it's the order of the __callbacks__ provided to `createServer` and `listen` that you're asking about, not the functions themselves, right? I think you need to reword your question to clarify that. Where you said _instruction_ I think you meant to say _callback_. And you're talking about http.createServer's callback or server.listen's callback. The way you worded it, it sounds like you're asking about which order the functions themselves will be called in. And surely there's no question about that. – Wyck Oct 25 '21 at 14:20

2 Answers2

0

If you look at the NodeJS documentation for the HTTP module here: https://nodejs.org/api/http.html#httpcreateserveroptions-requestlistener

You'll see what the http.createServer call returns, from the docs:

Returns a new instance of http.Server.

Thus the createServer call must complete before it can return a server object. Which is being used in your the server.listen call being made a few lines below. Asynchronous in NodeJS doesn't mean random.

Diego Mejia
  • 141
  • 8
0

http.createServer() is the first to execute because the variable server must be set before use to avoid undefined error. And the http.createServer is a synchrone function asynchronous-vs-synchronous

  • when callback function inside createServer exexute? – avishek kumar Oct 25 '21 at 14:19
  • The callback is waiting for requests before called. The request can be from browser, postman, curl or something like that – Rajaomaria Jaona Oct 25 '21 at 14:23
  • 1
    The callback to `createServer` is a handler for requests. You'll see the "Server running..." log message occur as soon as the server is in a listening state, and that will happen before any requests come in to be handled by the `(req, res)` handler. – Wyck Oct 25 '21 at 14:27