After all the literature i've read on node.js I still come back to the question, does node.js itself make use of multiple threads under the hood? I think the answer is yes because if we use the simple asynch file read example something has to be doing the work to read the file but if the main event loop of node is not processing this work than that must mean there should be a POSIX thread running somewhere that takes care of the file reading and then upon completion places the call back in the event loop to be executed. So when we say Node.js runs in one thread do we actually mean that the event loop of node.js is only one thread? Or am i missing something here.....
Every Node.js article introduces Node.js as single-threaded. Below are some misconceptions about multi-threading in Node.js. Just like JavaScript, Node.js doesn’t support multi-threading. Node.js is a proper multi-threaded language just like Java.
Earlier Development of Node: When Node was initially being developed, it followed the paradigm of one thread per request. This means that whenever a user made a request to the server, or requests were made from the database … a separate thread was created to complete that request.
Node.js is a cross-platform JavaScript runtime environment which helps to execute and implement server side programs. Node supports asynchronous processing of code, which leads us to the result that it is a single threaded platform. Let’s discuss in detail what is meant by Node being single threaded and why does it follow this method.
parentPort – An instance of MessagePort, it is used for communicating with the parent thread. threadId – A unique identifier assigned to the worker thread. workerData – Contains the data included in the worker thread’s constructor by the spawning thread. In order to harness the power of a multi-core system using Node.js, processes are available.
To a Javascript program on node.js, there is only one thread.
If you're looking for technicalities, node.js is free to use threads to solve asynchronous I/O if the underlying operating system requires it.
The important thing is to never break the "there is only one thread" abstraction to the Javascript program. If there are more threads, all they can do is queue up work for the main thread in the Javascript program, they can never execute any Javascript code themselves.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With