Home > Enterprise >  What does server.listen() actually do?
What does server.listen() actually do?

Time:10-22

Disclaimer: Über-noob.

This question may have more to do with how files are executed than what http or node do. I have the following simple-as-all-hell file that will be executed with node to make a local server.

const http = require("http");

const hostname = "127.0.0.1";
const port = 8000;

// Create http server
const server = http.createServer( function (req,res)  {
  // set response http header with http status and content type
  res.writeHead(200, {"Content-Type": "text/plain"});

  // send response "hello world"
  res.end("G'day mate\n");
});


// Listen on a given port and print a log when it starts listening

server.listen(port, hostname, () => {
  console.log("heyy maattteeeyyy")
});

My question: Why, when I enter the command node hello.js does this file keep executing / keep running? I presume it is something about the final server.listen() command that says "when you run this, just keep running, I am now hosting something", but what exactly is that?

Thank you

CodePudding user response:

The short answer it creates a process, that listens on hostname:port. So every query on this port will be processed by your app

The long answer is nodejs docs: https://nodejs.org/api/net.html#serverlisten

CodePudding user response:

Create a server that listens on port 8000 of your computer.

https://www.w3schools.com/nodejs/met_server_listen.asp

  • Related