How do I write non-blocking code in Node.js?

I can write non-blocking I/O in Node.js very easily. It's what the entire library is set up for.

But any computation done is blocking. Any message passing over event emitters are blocking.

For example, emitting events are resolved immediately and are thus blocking:

var e = new process.EventEmitter;
e.on("foo", function() {
    console.log("event");
});
process.nextTick(function() {
    console.log("next tick");
});
setTimeout(function() {
    console.log("timeout");
}, 0);
e.emit("foo");

> event
> next tick
> timeout

Apart from wrapping calls in nextTick, how do I make code non-blocking?

I want to do as little computation per cycle of the event loop as possible, so that I can serve as many clients simultaneously as possible.

How do I write my code in a non-blocking fashion?

And when I have non-blocking code, how do I scale that across multiple processes?

One option is waiting for the WebWorker sub-process API to be finished.

20
задан Peter Mortensen 12 January 2015 в 16:54
поделиться