Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
596 views
in Technique[技术] by (71.8m points)

node.js - When does Nodejs process quit?

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
');
}).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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...