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

2023-11-28

我正在尝试编写一个 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?
});

Try 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 观看文件的一些跨平台问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐