A filename can change observable behavior before any code changes. In Node.js, a plain .js file runs as CommonJS by default, while .mjs selects ECMAScript Modules. The runtime therefore changes both how the file is interpreted and how scheduled work is ordered. section 1.1 section 8.5.3
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'));Use the small scheduling puzzle to observe CommonJS behavior in Node.js rather than treating the output order as language-neutral. section 1.1
CommonJS is Node.js’s original module system: a module is one JavaScript file, and the module system determines how the runtime loads files and lets them share code. ECMAScript Modules are newer and built into the language, but Node.js loads the two systems differently. section 1.1
The distinction reaches beyond module syntax. Node.js executes a CommonJS script as a macrotask, then drains the nextTick queue before the microtask queue. An ECMAScript module runs as a microtask, so the same queued operations can reverse their apparent order. section 8.5.3
The extension changes the result
A scheduling script produces B, A, A, B as .js under Node.js. Renaming it to .mjs without changing its code produces A, B, B, A, because the execution context changes from CommonJS to an ECMAScript module. section 8.5.3
CommonJS behavior is consequently runtime-sensitive. The same code behaves differently across Node.js, Deno, Bun, browsers, and Cloudflare Workers; globals such as process.nextTick and setImmediate are not uniformly available. section 1.1
queueMicrotask(() => {
queueMicrotask(() => console.log('A'));
process.nextTick(() => console.log('B'));
});
process.nextTick(() => {
queueMicrotask(() => console.log('A'));
process.nextTick(() => console.log('B'));
});
Trace nested nextTick and microtask scheduling to see why CommonJS queue precedence produces surprising output. section 8.5.3




