Node.JS: How does "fs.watchFile" work?

700 Software picture 700 Software · Mar 22, 2011 · Viewed 18.3k times · Source

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?

Answer

beatgammit picture beatgammit · Apr 3, 2011

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.