使用node.js观察文件夹以进行更改,并在更改时打印文件路径

And*_*een 77 node.js

我正在尝试编写一个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?
});
Run Code Online (Sandbox Code Playgroud)

mts*_*tsr 126

试试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);})
Run Code Online (Sandbox Code Playgroud)

Chokidar解决了使用fs观看文件时的一些跨平台问题.

  • 它处理子文件夹吗? (5认同)
  • 一个问题 - 当我复制一个大文件时。添加事件会立即触发,然后随着文件复制的进行,我会收到数百个更改事件。有什么方法可以在文件复制结束时仅触发一个事件? (2认同)
  • @ Curious101,您是否尝试过添加`awaitWriteFinish:true`?默认情况下为假。 (2认同)

Kau*_*ani 32

为什么不用旧的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);
})
Run Code Online (Sandbox Code Playgroud)

有关选项参数的更多信息和详细信息,请参阅节点文件

  • 注意警告,我已经在我的mac上测试了这个,并且这段代码只检测文件夹级别而不是任何子目录进行更改,所以一定要确保添加选项以递归方式作为第二个参数观察; 查看上面链接的文档 (5认同)
  • @ThomasJayRush 一种机制,允许在事件和要发生的操作之间传递一定的时间,因此如果事件触发两次,则仅调用该操作一次。这是一个工程术语,物理按钮会触发电流,但按钮会“弹跳”一次或多次,从而在只需要一个的电流中产生多个尖峰 - 这也可以应用于编程 - 尤其是 JS。https://medium.com/@jamischarles/what-is-debouncing-2505c0648ff1 (4认同)
  • 添加了 @OzzyTheGiant 的注释:递归选项仅在 macOS 和 Windows 上受支持。 (2认同)

Sha*_* RB 11

试试猎犬:

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()
Run Code Online (Sandbox Code Playgroud)

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