How does a node.js application keep running when no new events are queued up?
My question is how does a node.js application, like a http server keep running even when no new events are present?
I thought the libuv event loop terminates when no new events are queued up.
Is it something like a while(true) {} loop with event listeners registered for events?
Here is a simple code example of my question:
var http = require("http");
var server = http.createServer(function(request, response) {
response.write("Hello World!");
response.end();
});
server.listen(8080);
Thanks
EDIT: We know from the the libuv io loop doc that the loop has to be alive at the beginning of each loop iteration, meaning more events occurred thus more callbacks are registered to be executed.
In this example, an event listener is registered but the program exits after the single event is handled because no more events were fired before the next loop iteration.
var EventEmitter = require('events').EventEmitter;
eventEmitter.on('event1', function() {
console.log('event1 has occured');
});
eventEmitter.emit('event1');
But in this example the program continues indefinitely because of the active timer.
setTimeout(function() {
console.log('setTimeout callback occured');
}, 2000);
So what is keeping the loop alive (the active and ref'd handles) in the http server example?
When you create the HTTP server, a TCP socket will be created, which is backed by a uv_tcp_t handle. Since the socket is active (listening for incoming connections) the loop will keep running until you stop the HTTP server.
Timers are a bit tome complex because each Node Timer does not map to a uv_timer_t handle, but the principle is the same.
链接地址: http://www.djcxy.com/p/52700.html上一篇: Node.js杀死一个异步调用