Node.js fs.watchFile persistent watch mechanics?

前端 未结 1 1375
有刺的猬
有刺的猬 2020-12-29 08:53

Can someone explain how persistent watch works?

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

Thanks ;)

相关标签:
1条回答
  • 2020-12-29 09:11

    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.

    0 讨论(0)
提交回复
热议问题