Although it is not entirely stable, the fs
module provides a useful tool for watching a file and executing a callback function when the file changes. This can be useful if you want to trigger events to occur when a file is modified but do not want to continually poll from your application directly. Watches do incur some overhead in the underlying operating system, so you should use them sparingly.
To implement a watch on a file, use the following command, passing the path
to the file you want to watch:
fs.watchFile(path, [options], callback)
You can also pass in options
, which is an object that contains persistent
and interval
properties. The persistent
property is true
if you want the process to continue to run as long as files are being watched. The interval
property specifies the time, in milliseconds, that you want the file to be polled for changes.
When a file change occurs, the callback
function is executed and passed current and previous Stats
objects.
The following code snippet monitors a file named log.txt
every 5 seconds and uses the Stats
object to output the current and previous times the file was modified:
fs.watchFile("log.txt", {persistent:true, interval:5000}, function (curr, prev) {
console.log("log.txt modified at: " + curr.mtime);
console.log("Previous modification was: " + prev.mtime);
});