Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does Nodejs process quit?

Tags:

node.js

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?

like image 741
Qian Chen Avatar asked Oct 31 '13 06:10

Qian Chen


People also ask

What does process exit do NodeJS?

The process. exit() method is used to end the process which is running at the same time with an exit code in NodeJS.

What is process Exit 1 in Node JS?

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.

How do I stop a node JS execution?

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.

Is node still popular 2022?

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.


1 Answers

[...] 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:

  • The event loop's queue is empty.
  • No background/asynchronous tasks remain that are capable of adding to the queue.

.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.

like image 106
Jonathan Lonowski Avatar answered Sep 20 '22 16:09

Jonathan Lonowski