A simple node program with a single line of code quits immediately after running all the code:
console.log('hello');
However, an http server program listening on a port does not quit after executing all code:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
So my question is, what made this difference? What made the first program quit after executing all code, while the second program continue to live?
I understand in Java, the specification says that when the last non daemon thread quits, the JVM quits. So, what is the mechanism in the nodejs world?
The process. exit() method is used to end the process which is running at the same time with an exit code in NodeJS.
It will let the Node. js know to terminate the process when no async operations are performing. Without mentioning, it will take the default value of 0. Exit Code 1. It is useful in case of fatal exceptions not handled by the domain.
Method 1: Using the Ctrl+C key I hope everyone knows this shortcut to exit any Node. js process from outside. This shortcut can be used to stop any running process by hitting this command on terminal.
js, introduced back in 2009, is not one of these. Node. js development has become very popular over the last four years and continues to stand the competition in 2022 making startups worldwide choose it over other available options.
[...] what made this difference? What made the first program quit after executing all code, while the second program continue to live?
The 2nd program .listen()
ed.
Node's mechanism is the event loop and a node
process will generally exit when:
.listen()
establishes a persistent task that is indefinitely capable of adding to the queue. That is, until it's .close()
d or the process is terminated.
A simple example of prolonging the 1st application would be to add a timer to it:
setTimeout(function () {
console.log('hello');
}, 10000);
For most of that application's runtime, the event queue will be empty. But, the timer will run in the background/asynchronously, waiting out the 10 seconds before adding the callback to the queue so that 'hello'
can be logged. After that, with the timer done, both conditions are met and the process exits.
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