我想写一个 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查看文件的跨平台问题.

Node.js相关问答推荐

使用NodeJS输出检索Base64图像的网络报废

@nuxtjs/站点 map 错误提示:找不到包';NitroPack';

带有apache Couch-db和Nano的推荐引擎:过滤特定用户的视图

如何在Angular jest测试中调用Nodejs的垃圾收集? node v20的测试速度慢且内存泄漏

如何防止Socket-io实例化React/Next.js中的两个套接字(当前在服务器*和*客户端实例化)

FiRestore UPDATE方法引发错误:&Quot;错误:13内部:收到代码为1&Quot;的RST_STREAM

如何修复node.js中的错误代码无法加载资源:服务器响应状态为403(禁止)

Node.js中使用ffmpeg如何获取视频截图的位置?

Cypress.io - 如何等待返回调用属性的方法的结果?

AWS ECS 服务发现 Cors 问题?

使用 NPM 三个 mocha+typescript 进行测试

每秒从套接字传来的数据有哪些存储方式?

带有 node.js 和 express 的基本网络服务器,用于提供 html 文件和assets资源

Puppeteer 错误:未下载 Chromium 修订版

Dart 语言比 JavaScript (Node.js) 有什么好处

向 Stripe 提交付款请求时出现没有此类令牌错误

如何在 Joi 字符串验证中使用枚举值

使用 Node.js 我得到错误:EISDIR,读取

响应分块时获取整个响应正文?

将 expressjs 绑定到特定的 IP 地址