一尘不染

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

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?
});

阅读 230

收藏
2020-07-07

共1个答案

一尘不染

试试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即可查看文件,从而解决了一些跨平台问题。

2020-07-07