A professional application will likely log information about usage, cache pre-rendered data views, or make other changes to files and directory structures.
Node allows developers to register for notifications on file events through the fs.watch method.
The watch method broadcasts changed events on both files and directories.
This example will set up a watcher on itself, change its own filename, and exit:
const fs = require('fs');
fs.watch(__filename, { persistent: false }, (event, filename) => {
console.log(event);
console.log(filename);
})
setImmediate(function() {
fs.rename(__filename, __filename + '.new', () => {});
});
Alternatively, use a third-party package! If you encounter difficulties with a Node module, check npm for alternatives. Here, as a problem-fixing wrapper on top of fs.watch , consider Paul Miller's chokidar. It is used as the file-watching tool for build systems like gulp, and in many other projects. Refer to: