node. js How to Monitor File Changes
- 2021-08-09 06:56:34
- OfStack
fs.FSWatcher
The fs. FSWatcher class inherits EventEmitter and is used to monitor file changes. After calling fs. watch, one fs. FSWatcher instance is returned. Whenever the specified monitored file is modified, the instance will trigger an event to call the callback function
fs.watch('./tmp', (eventType, filename) => {
if (filename) {
console.log(filename);
}
});
fs.watch()
fs.watch(filename[, options][, listener])
Monitor file changes and return fs. FSWatcher instances
1. filename: File or folder path
2.options
eventType is mainly
rename
And
change
On most platforms, the 'rename' event is triggered when a file appears or disappears from a directory. On Windows, no event is triggered if the monitored directory is moved or renamed, and when the monitored directory is deleted, it is reported
EPERM
Errors
fs.watch('./', { recursive: true }, (eventType, filename) => {
console.log(eventType, filename);
});
fs.watchFile()
fs.watchFile(filename[, options], listener)
Used to monitor file changes
1.filename
2.options
3. listener (currentStats, previousStats): listener has two parameters, the current stat object and the previous stat object
To receive notifications when a file is modified, you need to compare the
curr.mtime
And
prev.mtime
const fs = require('fs');
fs.watchFile('./test.txt', { interval: 100 }, (curr, prev) => {
console.log(' The current last modification time is : ' + curr.mtime);
console.log(' The last modification time before is : ' + prev.mtime);
});
const tid = setInterval(() => {
fs.appendFile('./test.txt', 'Hello, world!\n', err => {
if (err) throw err;
console.log(' File modification completed ');
});
}, 300);
setTimeout(() => {
clearInterval(tid);
fs.unwatchFile('./test.txt');
}, 2000);
fs. watch () and fs. watchFile ()
Because fs. watchFile () uses rotation to detect file changes, if you do not set the
interval
Or if you set a higher value, you will find that there is a delay in monitoring file changes
While fs. watch () listens for events provided by the operating system and can monitor directory changes, using fs. watch () is more efficient than fs. watchFile (). Generally, fs. watch () should be used instead of fs. watchFile () as much as possible
Of course, fs. watch () depends on the implementation of the operating system and will behave differently on different platforms
The Linux operating system uses inotify Using FSEvents in macOS system Using ReadDirectoryChangesW in windows system
fs.unwatchFile
fs.unwatchFile(filename[, listener])
Stop monitoring filename changes. If listener is specified, only this specific listener is removed. Otherwise, all listeners are removed, thus stopping monitoring filename
fs.unwatchFile('./test.txt');
Community choice
fs. watchFile () performance problem, fs. watch () platform is not 1, and so on two methods have unsatisfactory place
Node.js
rename
0
:
MacOS sometimes does not provide filename
Modification events are not triggered in some scenarios (MacOS Sublime)
Often modify once and trigger twice
Most file changes eventType are rename.
No simple way to monitor file trees is provided
Node.js
fs.watchFile
:
Event handling issues and fs. watch 1
No nested listening
CPU consumes a lot
https://www.npmjs.com/package/chokidar
Daily monitoring of file changes can choose excellent solutions in the community
node-watch chokidar
const chokidar = require('chokidar');
// One-liner for current directory
chokidar.watch('.').on('all', (event, path) => {
console.log(event, path);
});
// Initialize watcher.
const watcher = chokidar.watch('file, dir, glob, or array', {
ignored: /(^|[\/\\])\../, // ignore dotfiles
persistent: true
});
// Something to use when events are received.
const log = console.log.bind(console);
// Add event listeners.
watcher
.on('add', path => log(`File ${path} has been added`))
.on('change', path => log(`File ${path} has been changed`))
.on('unlink', path => log(`File ${path} has been removed`));
// More possible events.
watcher
.on('addDir', path => log(`Directory ${path} has been added`))
.on('unlinkDir', path => log(`Directory ${path} has been removed`))
.on('error', error => log(`Watcher error: ${error}`))
.on('ready', () => log('Initial scan complete. Ready for changes'))
.on('raw', (event, path, details) => { // internal
log('Raw event info:', event, path, details);
});
These are the details of how node. js monitors file changes. For more information about node. js monitoring files, please pay attention to other related articles on this site!