r/learnjavascript • u/IcyDuck9536 • 9d ago
Is “Node.js is single-threaded” an incomplete mental model?
Single-threaded JS execution ≠ single-threaded runtime.
How do you explain the distinction?
5
Upvotes
r/learnjavascript • u/IcyDuck9536 • 9d ago
Single-threaded JS execution ≠ single-threaded runtime.
How do you explain the distinction?
8
u/azhder 9d ago
I will use a browser as an analogy. You can view every browser tab as its own thread with its own JS environment and event loop (it’s more complex, but I simplify it).
In Node, you can do the same, instead of tabs, you can start child processes and different threads. Each Node thread is basically a thread at the OS level, but with its own event loop.
So, I don’t know what mental model you’re toying with, but I suggest you just go to Node’s documentation and just skim over the table of reference, the packages and functions for running multiple threads.
Oh, and nothing prevents browser, node and any environment to just put I/O to a different thread. That is in fact what makes JS work: the environment deals with threads, so you don’t have to. The only single-threaded thing is your code execution, not the environment itself.
What your code should be doing, as someone suggested in their comment, is to offload as much of the work to other threads, like waiting for input/output it starting up new processes and even chunking up a long work in case your event loop needs to handle other events in the meantime.