I am very new to node.js and first thing that I could not easily google is following. Consider the most typical node.js example:
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');
console.log('Server running at http://127.0.0.1:1337/');
How will node.js know that it should not exit after last line has executed? Coming from .NET I have a simplified assumption that the process exits when all of its non-background threads are terminated. As node.js is single-threaded, I believe that there should be some logic monitoring event subscriptions which will decide whether there are still events which may be triggered, or otherwise node.js can terminate. Unfortunately, I could not find any docs on that. Could anyone help?
If you are from .NET background, you might have written some of the ASP.NET web application hosted over IIS. In this case your .NET framework creates a pool of application thread to handle the incoming request, your page gets executed and the response is sent back to the client. Thus your page execution is being handled by .NET framework. In whole process IIS keeps on listening the incoming request and handle over the request to appropriate workers/threads.
Node.JS works in same manner where you just instructed the Node to how to process the request. When you create a server, node opens the socket to listen for incoming request. However since there is no close command written, your server will keep on running.
To understand how node handles/process the request, please visit
http://strongloop.com/strongblog/node-js-performance-event-loop-monitoring/
http://strongloop.com/strongblog/node-js-event-loop/
To learn how to close the server visit http://nodejs.org/api/net.html#net_server_close_callback