I'm writing some node.js code in which I would like to trigger action when a file is loaded to a directory, or when that file is updated there --I'm expecting that the same file name will be replaced in the directory repeatedly.
So, when the node child process finishes saving a file to the watched directory, I would like to trigger subsequent processes that use that file:
This thread seemed related, but not quite explicit enough about how to know when the file is updated or replaced: Watch a folder for changes using node.js, and print file paths when they are changed
Implicitly, I also need to verify that the updating process to the file in the watched directory is complete before the next events would be triggered.
Thanks as always for your advice!
I think the thread you linked it pretty explicit, isn't it? You can either use the standard methods fs.watch
and fs.watchFile
, or a nice little wrapper such as https://github.com/paulmillr/chokidar . ie:
var chokidar = require('chokidar');
var watcher = chokidar.watch('dir/', {ignored: /^\./, persistent: true});
watcher
.on('add', function(path) {console.log('File', path, 'has been added');})
You can use notify
as well.
var Notify = require('fs.notify');
var files = [
'/path/to/file',
'/file/i/want/to/watch'
];
var notifications = new Notify(files);
notifications.on('change', function (file, event, path) {
console.log('caught a ' + event + ' event on ' + path);
});
// if you want to add more files you can use the
notifications.add([path, morepaths]);
// kill everything
notifications.close();
But chokidar
is better.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.