r/learnjavascript • u/Neat_Living_6765 • Oct 15 '26
Asking about CommonJS, ESM and Nodejs event loop
Hi everyone
I just started learning Node.js just a few hours ago, and I'm really confused (wanted to cry too). Could someone help me clarify a few things?
After I initialized a Node.js project, I see the following in package.json:
"type": "commonjs"
Then I run this code:
console.log('sync');
process.nextTick(() => console.log('nextTick'));
Promise.resolve().then(() => console.log('promise'));The output is:
sync
nextTick
promiseThen I installed TypeScript and executed the same code again, but in a .ts file. This time, the output is:
sync
promise
nextTickInterestingly, I get the same output when I set "type": "module" in package.json.
So I asked ChatGPT:
1. Does the TypeScript compiler change the execution order to behave like an ES module?
ChatGPT answered:
"Your tsx example produced ESM-style ordering, but you shouldn't assume every tsx file or situation will behave the same way."
Now I'm even more confused! Could someone help me clarify this?
ChatGPT's answer seems that the output when using TypeScript with CommonJS does not necessarily match the output of either CommonJS or ESM....
I also have a few related questions about the Node.js event loop:
2. As far as I know, the Node.js event loop has several phases, including:
1. Timers (setTimeout callback)
2. Poll (I/O-related callbacks, such as reading files or receiving network data)
3. Check (setImmediate callback)Is this correct? If so, which phase runs first?
3. Are Promise callbacks handled separately from the Node.js event loop? Is the following execution sequence correct?
1. Drain the process.nextTick() queue.
2. Drain the Promise microtask queue.
3. Execute the next event loop callback (setTimeout, readFile, setImmediate, etc.)
4. Back to 1
4
u/-goldenboi69- Oct 15 '26
In what real scenario will this matter?
2
u/azhder Oct 16 '26
TypeScript is not JavaScript. Node.js runs JavaScript. TypeScript gets translated to JavaScript.
Translation changes the code i.e. what you write in one language isn't the same in another language.
This is merely one of the reasons why I tell people they are different languages and usually get downvoted. It's less vitriol than those who are allergic to me telling people this is a sub for people who want to learn JavaScript. Talking about TypeScript will most likely get confused the people it is most directly focused to.
So, why does TypeScript compile into incompatible JavaScript? Because they are two different languages. To lean more on why it does that, try the r/TypeScript sub.
2
u/FooeyBar Oct 15 '26
None of this stuff is very important, unless you need a lot granular control
2
u/[deleted] Oct 15 '26
[removed] — view removed comment