Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why node server.listen do not returns to shell

Node files can describe from servers to simple scripts, even something that only prints to console:

//logger.js
console.log('Hello World');

// in the terminal
> node logger.js
Hello World
>

How http package (and others) do not give the command prompt back to the user; how do they keep the process alive?

//server
require('http').createServer(function (req, res) {
  res.end('Hello World');
}).listen(3000);

// in the terminal
> node server.js
// process stays in the foreground, no prompt back
like image 719
yves amsellem Avatar asked Dec 19 '22 04:12

yves amsellem


2 Answers

Node will not exit if there is a socket that is listening. So that's the TL;DR answer. (The other answers talking about the event queue are correct about that being a possible cause of programs not exiting, but that is not what is going on with server.listen().)

Under the hood, http.createServer() is (eventually) calling server.listen() Calling server.listen() will keep the process from exiting because server.listen() creates a socket. Note from the docs for socket.ref():

Opposite of unref, calling ref on a previously unrefd socket will not let the program exit if it's the only socket left (the default behavior). If the socket is refd calling ref again will have no effect.

And socket.unref():

Calling unref on a socket will allow the program to exit if this is the only active socket in the event system. If the socket is already unrefd calling unref again will have no effect.

If you want to go the next level in from there, I believe you would need to dive into the C or C++ the underlies Node.js/io.js.

like image 93
Trott Avatar answered Jan 02 '23 05:01

Trott


Node will quit when there is no event in event queue and no background task exists(which can add event to event queue) in your case, it's the later.

like image 30
user2786771 Avatar answered Jan 02 '23 05:01

user2786771