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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With