When does the Nodejs process end?

A simple node program with one line of code exits immediately after all the code runs:

console.log('hello');

However, the HTTP server program listening on the port does not exit after all the code has been executed:

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 did it mean? What made the first program exit after all the code was executed, and the second program continues to live?

I understand that in Java, the specification says that when exiting the last thread of a non-daemon, the JVM shuts down. So what is the mechanism in the nodejs world?

+4
source share
3 answers

[...] what made this difference? What made the first program exit after all the code was executed, and the second program continues to live?

.listen() ed.

Node , node , :

  • .
  • / , .

.listen() , ​​ . , .close() d .

:

setTimeout(function () {
    console.log('hello');
}, 10000);

. /, 10 , 'hello' . , .

+8

, , . , . , Node.js :

// watcher.js - watches a text file for changes.
const fs = require('fs');

fs.watch('target.txt', function() {
    console.log("Target.txt just changed!");
});

console.log("Watching target.txt");

node --harmony watcher.js.

; CTRL + C.

0

Node.js . , Node.js .

-- , .

The HTTP server program behaves differently. It creates a server and associates it with a port. At the same time, it registers a handler that will be called whenever a new HTTP connection is established. When the end of the program code is reached, there is one active event listener and the program continues to work.

You can complete the server program by releasing server.close()after a while.

0
source

All Articles