Наблюдайте за папкой изменений с помощью node.js и печатайте пути к файлам при их изменении
Я пытаюсь написать node.js script, который следит за изменениями в каталоге файлов, а затем печатает файлы, которые были изменены. Как я могу изменить этот script так, чтобы он смотрел каталог (а не отдельный файл) и печатал имена файлов в каталоге по мере их изменения?
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
Попробуйте 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.
Ответ 2
Почему бы просто не использовать старый 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);
})
Подробнее о параметрах param см. Node fs Docs
Ответ 3
попробуйте hound:
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()
Он будет выполняться после изменения файла