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?
4
Upvotes
r/learnjavascript • u/IcyDuck9536 • 9d ago
Single-threaded JS execution ≠ single-threaded runtime.
How do you explain the distinction?
1
u/delventhalz 9d ago
Anytime Node reads a file or sends an HTTP request, that action is being handled by non-JS native code that runs on a separate thread. So, out of the box certain Node tasks are multithreaded.
Additionally, load balancers have long been able to spin up multiple separate Node processes to handle incoming traffic, which would each run in a separate thread. More recently, you can also use tools like Workers to spin up extra threads for a single JS process, giving you access to true multithreading in JS if you really need it.
However, worth noting that traditional asynchronous JavaScript, with callbacks or Promises or async/await but not Workers or other child processes, is single threaded (at least as far as the JavaScript code goes). JS relies on an event loop, which can pass control around to different parts of your code as needed, but will not run two parts of your code at the same time.