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

ベストアンサー1

試すチョキダール:

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 のみを使用してファイルを監視する際のクロスプラットフォームの問題の一部を解決します。

おすすめ記事