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



답변

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 만 사용하여 파일을 보는 것과 관련된 몇 가지 크로스 플랫폼 문제를 해결합니다.


답변

왜 그냥 오래된 것을 사용하지 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);
})

옵션 매개 변수에 대한 자세한 정보 및 세부 사항은 Node fs 문서를 참조하십시오.


답변

사냥개 시도 :

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

파일이 변경되면 실행됩니다.


답변