Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js fs.watchFile persistent watch mechanics?

Tags:

node.js

Can someone explain how persistent watch works?

Does it eat some resources on the PC if it is watching file(s) for changes?

Thanks ;)

like image 302
Somebody Avatar asked Dec 19 '10 09:12

Somebody


1 Answers

fs.watchFile creates a StatWatcher which then performs a stat on the file that's being watched. How exactly that happens at the low level (besided doing the obvious stats call) is dependent on the event loop implementation with which node was compiled.

So yes, it takes up a bit of CPU, but at you can't do anything else besides polling here, that is, unless the underlying file system itself would issue the file change events.

See:
https://github.com/ry/node/blob/v0.3.2/lib/fs.js#L472
https://github.com/ry/node/blob/v0.3.2/src/node_stat_watcher.h#L39
https://github.com/ry/node/blob/v0.3.2/src/node_stat_watcher.cc#L78

Some more info on the parameters

Interval is relavent where inotify is not available - it determines how long to poll for updates. Persistent has to do with how the program should act when nothing but watchFile is running. The default is to exit.

As far as I saw, it takes 3--5 seconds to notice the changes (with the default settings), can i make it faster?

On linux it uses inotify - which is faster

how heavy is watching hundreds of files?

Heavy. It's not meant for that.

Source: Post on the Node.js Google Group by Ryan Dahl

In conclusion
If you're on linux, the interval option has no effect et all.
If you don't set persistent and there's nothing else in the event loop besides the file watcher, the program will exit.

like image 195
Ivo Wetzel Avatar answered Sep 21 '22 14:09

Ivo Wetzel