Reputation: 1
For the below code,
var fs = require('fs');
fs.watch('target.txt', function(event, fileName){
console.log('Event: ' + event + ', for file: ' + fileName);
});
Console.log('Now watching target.txt');
As per the below architecture,
1) fs.watch()
will invoke libuv
. libuv
will launch a thread to track change
event on target.txt
. The result from libuv
will go to v8
and again through NodeJS Bindings
in the form of callback with a buffer having data.
2) libuv
adds change
event in Event queue. As the event loop picks the change
event, corresponding call back is executed in v8
run time.
Is my understanding correct?
Upvotes: 3
Views: 744
Reputation: 77063
No, you misunderstand it. NodeJS does not have threads, it is single-threaded instead, using the Observer Pattern. The event loop waits for events to occur (to observe an event). When an event is occurred, then it calls its handler. The illusion of multi-threaded approach comes from the fact that Node frequently uses async events, defining callback functions to be executed when a given task is finished. Read more here.
Upvotes: 1