使用node.js监视文件夹的更改,并在更改时打印文件path

我正在尝试编写一个node.js脚本,用于监视文件目录中的更改,然后打印已更改的文件。 我该如何修改这个脚本,以便它可以监视一个目录(而不是一个单独的文件),并在目录更改时在目录中打印这些文件的名称?

var fs = require('fs'), sys = require('sys'); var file = '/home/anderson/Desktop/fractal.png'; //this watches a file, but I want to watch a directory instead fs.watchFile(file, function(curr, prev) { alert("File was modified."); //is there some way to print the names of the files in the directory as they are modified? }); 

尝试Chokidar :

 var chokidar = require('chokidar'); var watcher = chokidar.watch('file or dir', {ignored: /^\./, persistent: true}); watcher .on('add', function(path) {console.log('File', path, 'has been added');}) .on('change', function(path) {console.log('File', path, 'has been changed');}) .on('unlink', function(path) {console.log('File', path, 'has been removed');}) .on('error', function(error) {console.error('Error happened', error);}) 

Chokidar只用fs就可以解决一些跨平台的问题。

试试猎犬 :

 hound = require('hound') // Create a directory tree watcher. watcher = hound.watch('/tmp') // Create a file watcher. watcher = hound.watch('/tmp/file.txt') // Add callbacks for file and directory events. The change event only applies // to files. watcher.on('create', function(file, stats) { console.log(file + ' was created') }) watcher.on('change', function(file, stats) { console.log(file + ' was changed') }) watcher.on('delete', function(file) { console.log(file + ' was deleted') }) // Unwatch specific files or directories. watcher.unwatch('/tmp/another_file') // Unwatch all watched files and directories. watcher.clear() 

一旦文件发生变化,它就会执行

为什么不使用旧的fs.watch ? 它非常简单。

 fs.watch('/path/to/folder', (eventType, filename) => { console.log(eventType); // could be either 'rename' or 'change'. new file event and delete // also generally emit 'rename' console.log(filename); }) 

有关选项param的更多信息和详细信息,请参阅Node fs Docs