Node.JS: How does “fs.watchFile” work?

二次信任 提交于 2019-11-28 19:05:47

问题


According to the API docs for Node 0.4.3, the fs.watchFile(filename, [options], listener) function starts a routine that will

Watch for changes on filename. The callback listener will be called each time the file is accessed.

It also says

The options if provided should be an object containing two members a boolean, persistent, and interval, a polling value in milliseconds

Which indicates that it will check every so often based on what is in interval. But it also says

The default is { persistent: true, interval: 0 }.

So does that mean it will check every millisecond to see if the file time changed? Does it listen for OS level events? How does that work?


回答1:


Yes, cpedros is correct, this does seem to be a duplicate. I think I can shed some more light on this though.

Each OS has its own file change event that gets fired. On Linux, it is inotify (used to be dnotify), on Mac it is fsevents, and on Windows it is FileSystemWatcher. I'm not sure if the underlying code handles each case, but that's the general Idea.

If you just want to watch a file on Linux, I recommend node-inotify-plus-plus. If you want to watch a directory, use inotify-plus-plus with node-walk. I've implemented this and it worked like a charm.

I can post some code if you're interested. The beauty behind node-inotify-plus-plus is that it abstracts much of the nastiness of inotify and gives an intuitive API for listening to specific events on a file.

EDIT: This shouldn't be used to watch tons of files. On my system, the max is 8192. Your max can be found by using this command cat /proc/sys/fs/inotify/max_user_watches. This could be used to just watch directories for changes and then figure out the individual files from there. A modified event will fire if a file directly under that directory is modified.

EDIT: Thanks @guiomie for pointing out that watching files is now fully supported on Windows. I assume this is with the v0.6.x release.




回答2:


To extend on tjameson's fantastic answer, you could use watchr to normalise the API between the node versiosn and OS watching differences. It also provides events for unlink and new instead of just change, as well as adds support for directory tree watching.



来源:https://stackoverflow.com/questions/5394620/node-js-how-does-fs-watchfile-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!