A slow Node.js application can use promises, streams, and the event loop correctly at the API level yet still suffer from scheduling mistakes. Node.js executes JavaScript outside the browser, but JavaScript alone does not determine when every callback runs: the runtime and its module system matter too. section 1.1
One script, two outputs
Schedule five writes using queueMicrotask(), process.nextTick(), setTimeout(), Promise.then(), and setImmediate(). On Node.js 24, running the script as CommonJS prints “Hello”; running it as an ECMAScript module prints “elHo” followed by “l” on the next line. The filename’s module interpretation changes the result, so predict the output for the actual runtime and module format—not for JavaScript in the abstract. section 1.1
Listing 1.1 A friendly puzzle
function print(a) {
process.stdout.write(a);
}
queueMicrotask(() => print('e'));
process.nextTick(() => print('H'));
setTimeout(() => print('l'), 0);
Promise.resolve().then(() => print('l'));
setImmediate(() => print('o\n'));The small scheduling puzzle makes the competing callbacks visible as individual characters. section 1.1
The distinction matters in stream processing. A Node.js stream’s end event means it has finished emitting data, not that asynchronous work started by data handlers has finished. Track the transform promises and await Promise.all() at end, or consume the stream with for-await-of and await the pending work afterward. section 8.5.4
const results = [];
readable.on('data', async (chunk) => {
const processed = await transform(chunk); // async work
results.push(processed);
});
readable.on('end', () => {
console.log(`Processed ${results.length} chunks`);
// Often prints 0 or fewer than expected!
});
The data handler awaits a transform, but the end handler reads results without waiting for those transforms. section 8.5.4
Node.js also defines recovery behavior beyond JavaScript’s Error types. Use an error’s code for programmatic decisions and its message for human debugging; matching message text can break after even a punctuation change. For Node.js streams, handle error events: an unhandled event can crash the process, and pipe() does not forward source errors or clean up the destination. pipeline() propagates errors and destroys the chain. section 7.3 section 10.6.1





