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

问题描述 投票:0回答:2

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

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

这个帖子似乎有关,但不太清楚如何知道文件何时更新或替换:Watch a folder for changes using node.js, and print file paths when they are changed

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

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

javascript node.js socket.io watch
2个回答
2
投票

我认为你把它链接的线程很明确,不是吗?您可以使用标准方法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');})

0
投票

你也可以使用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更好。

© www.soinside.com 2019 - 2024. All rights reserved.