Reputation: 9445
Javascript is single threaded. So every piece of code which I write is executed in a single thread of javascript runtime provided by Node. So when I execute following code:
var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
// Synchronous read
var data = fs.readFileSync('input.txt');
Following is my understanding of workflow, please correct me if I am wrong:
fs.readFile
is popped off the call stack by manager in Node immediately and moved to some other thread where it starts the reading stuff.
When reading is complete, manager in Node:
fs.readFile
in the queue stackfs.readFileSync
is not popped off the stack but is executed in the runtime thread itself like any other function.
So, who is this manager in node which executes Node API I/O functions in other threads and manages their call stacks.
So does Node use multi-cores to execute it's API functions in the background?
Upvotes: 1
Views: 2160
Reputation: 2986
NodeJS is using event loop for asynchronous operations.
If you know, there is a library exists called libuv. libuv is responsible for asynchronous code execution. Here is a little pseudo-code how it managing this:
while there are still events to process:
e = get the next event
if there is a callback associated with e:
call the callback
You can read more about libuv here - http://nikhilm.github.io/uvbook/introduction.html
So, basically:
Do Node.js API functions execute in separate threads?
Both, yes and no. If function can move I/O operation to separate thread in thread-pool then yes. Otherwise it executes in the same thread.
So, who is this manager in node which executes Node API I/O functions in other threads and manages their call stacks?
libuv - https://github.com/libuv/libuv
So does Node use multi-cores to execute it's API functions in the background?
I don't know for sure, anyone can correct me if I'm wrong, but Node is executes within single-core. If you want to run with multi-core support, you need run it in cluster-mode.
UPD: Here is a little diagram that can help you to understand.
Upvotes: 3
Reputation: 751
While looking for resources to quote on answering this I couldn't actually find any that go into much detail. There's a nice intro here and some details on how the event loop works on MDN
It seems that there is another thread internal to the V8 engine which manages the event loop. This will take responses from things like operating system I/O and add the data and relevant callback to the queue. Every time the event loop finishes what it's doing it picks the next thing from the queue.
Upvotes: 0