Home > OS >  What is the order of execution of instruction in creating server in node.js?
What is the order of execution of instruction in creating server in node.js?

Time:10-26

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}/`);
});

CodePudding user response:

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.

CodePudding user response:

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

  • Related