将文件添加到目录时,在node.js中获取通知

Get notification in node.js when file is added to directory

本文关键字:node js 通知 获取 添加 文件      更新时间:2023-09-26

我正在编写一些node.js代码,在这些代码中,当一个文件加载到一个目录时,或者当该文件在那里更新时,我希望触发操作——我希望在目录中重复替换相同的文件名。

因此,当节点子进程完成将文件保存到监视目录时,我想触发使用该文件的后续进程:

这个线程似乎是相关的,但对于如何知道文件何时更新或替换还不够明确:使用node.js观察文件夹中的更改,并在更改文件路径时打印

隐含地说,在触发下一个事件之前,我还需要验证监视目录中文件的更新过程是否完成。

一如既往地感谢你的建议!

我认为你链接的线程非常明确,不是吗?您可以使用标准方法fs.watchfs.watchFile,也可以使用诸如https://github.com/paulmillr/chokidar.即:

var chokidar = require('chokidar');
var watcher = chokidar.watch('dir/', {ignored: /^'./, persistent: true});
watcher
  .on('add', function(path) {console.log('File', path, 'has been added');})

您也可以使用notify

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();

chokidar更好。