使用node.js监视文件夹中的更改,并在更改时打印文件路径 [英] Watch a folder for changes using node.js, and print file paths when they are changed

查看:71
本文介绍了使用node.js监视文件夹中的更改,并在更改时打印文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个node.js脚本,该脚本监视文件目录中的更改,然后打印更改的文件.如何修改此脚本,以便它监视目录(而不是单个文件),并在更改文件时显示目录中的文件名?

I'm trying to write a node.js script that watches for changes in a directory of files, and then prints the files that are changed. How can I modify this script so that it watches a directory (instead of an individual file), and prints the names of the files in the directory as they are changed?

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

Chokidar solves some of the crossplatform issues with watching files using just fs.

这篇关于使用node.js监视文件夹中的更改,并在更改时打印文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆