112

ファイルのディレクトリの変更を監視し、変更されたファイルを出力する 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?
});
4

3 に答える 3

178

チョキダーを試す:

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 だけを使用してファイルを監視することで、クロスプラットフォームの問題のいくつかを解決します。

于 2012-12-04T15:06:17.007 に答える
58

なぜ古いものを使わないの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);
})

options パラメータの詳細については、Node fs のドキュメントを参照してください。

于 2017-06-16T11:42:00.670 に答える
15

猟犬を試してください:

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()

ファイルが変更されると実行されます

于 2014-10-23T08:31:14.370 に答える