node.js 파일 변화 감시 방법

fs.FSWatcher
fs.FSWatcher 클래스는 EventEmitter를 계승하여 파일 변화를 감시하고 fs를 호출합니다.watch 후 fs를 반환합니다.FSWatcher 인스턴스, 지정된 모니터링 파일이 수정될 때마다 이벤트 호출 콜백 함수

fs.watch('./tmp', (eventType, filename) => {
 if (filename) {
  console.log(filename);
 }
});
fs.watch()fs.watch(filename[, options][, listener]) 파일 변화를 감시하고 fs로 돌아갑니다.FSWatcher 인스턴스
1.filename: 파일 또는 폴더 경로
2.options
  • encoding
  • recursive: 기본값false, 모든 하위 디렉터리를 감시해야 합니까, 아니면 현재 디렉터리만 감시해야 합니까, macOS와 Windows에서만 지원합니까
  • persistent: 기본값true, 파일이 감시되고 있으면 프로세스가 계속 실행되어야 하는지 지시
  • listener(eventType, filename): 파일 변화 콜백 함수
  • eventType은 주로 renamechange 대부분의 플랫폼에서 파일이 디렉터리에 나타나거나 사라질 때'rename'이벤트를 터치하고, Windows에서는 감시하는 디렉터리가 이동하거나 이름을 바꾸면 아무런 이벤트도 터치하지 않으며, 감시하는 디렉터리가 삭제되면 보고EPERM 오류
    
    fs.watch('./', { recursive: true }, (eventType, filename) => {
     console.log(eventType, filename);
    });
    fs.watchFile()fs.watchFile(filename[, options], listener) 파일 변경 모니터링
    1.filename
    2.options
  • biginit: 기본값false, 리셋stat의 수치가biginit 형식인지 지정
  • persistent: 기본값true, 파일이 감시되고 있을 때 프로세스가 계속 실행되어야 하는지 여부
  • interval: 기본값 5007, 폴링 주파수 지정(ms)
  • 3.listener(currentStats,previousStats):listener는 두 개의 매개 변수가 있습니다. 현재stat 대상과 이전stat 대상입니다.
    파일을 수정할 때 알림을 받으려면 비교curr.mtime prev.mtime
    
    const fs = require('fs');
    
    fs.watchFile('./test.txt', { interval: 100 }, (curr, prev) => {
     console.log(' : ' + curr.mtime);
     console.log(' : ' + prev.mtime);
    });
    
    const tid = setInterval(() => {
     fs.appendFile('./test.txt', 'Hello, world!
    ', err => { if (err) throw err; console.log(' '); }); }, 300); setTimeout(() => { clearInterval(tid); fs.unwatchFile('./test.txt'); }, 2000);
    fs.watch () 및 fs.watchFile()
    왜냐하면watchFile () 는 윤훈 방식으로 파일 변화를 감지합니다. 설정하지 않거나 높은 값을 설정하면 파일 변화에 대한 감시가 지연됩니다.
    fs.watch()는 운영체제가 제공하는 이벤트를 감청하고 디렉터리 변화를 감시할 수 있으며 fs를 사용합니다.watch () 비 fs.watchFile () 은 보다 효율적이며 평상시에는 가능한 한 fs를 사용해야 합니다.watch () 대신 fs.watchFile()
    물론watch()는 운영체제의 실현에 의존하여 서로 다른 플랫폼에서 나타나는 차이가 있다
  • Linux 운영 체제는 inotify
  • 를 사용합니다.
  • macOS 시스템에서 FSEvents
  • 사용
  • 윈도우즈 시스템에서 ReadDirectoryChangesW
  • 사용
    fs.unwatchFileintervalfilename의 변화를 감시하지 마십시오.listener를 지정하면 이 특정 감청기만 제거하고, 그렇지 않으면 모든 감청기를 제거하여 filename 감시를 중지합니다fs.unwatchFile(filename[, listener]) 커뮤니티 선택
    fs.watchFile () 성능 문제, fs.watch() 플랫폼이 일치하지 않는 등 두 가지 방법이 모두 마음에 들지 않는 부분이 있다
    Node.js fs.unwatchFile('./test.txt'); :
    MacOS에서 filename 을 제공하지 않는 경우가 있습니다.
    일부 장면에서 수정 이벤트를 트리거하지 않음(MacOS Sublime)
    자주 한 번에 두 번 트리거 이벤트 수정
    대부분의 파일 변경 eventType은 rename입니다.
    간단한 파일 트리 모니터링 방식이 제공되지 않음
    Node.js fs.watch :
    이벤트 처리 문제 및 fs.시계처럼 썩다
    중첩된 감청 없음
    CPU 사용량이 많음
    https://www.npmjs.com/package/chokidar
    일상적인 파일 변화 감시에서 지역사회의 우수한 방안을 선택할 수 있다
  • node-watch
  • chokidar
  • 
    const chokidar = require('chokidar');
     
    // One-liner for current directory
    chokidar.watch('.').on('all', (event, path) => {
     console.log(event, path);
    });
    
    // Initialize watcher.
    const watcher = chokidar.watch('file, dir, glob, or array', {
     ignored: /(^|[\/\\])\../, // ignore dotfiles
     persistent: true
    });
     
    // Something to use when events are received.
    const log = console.log.bind(console);
    // Add event listeners.
    watcher
     .on('add', path => log(`File ${path} has been added`))
     .on('change', path => log(`File ${path} has been changed`))
     .on('unlink', path => log(`File ${path} has been removed`));
     
    // More possible events.
    watcher
     .on('addDir', path => log(`Directory ${path} has been added`))
     .on('unlinkDir', path => log(`Directory ${path} has been removed`))
     .on('error', error => log(`Watcher error: ${error}`))
     .on('ready', () => log('Initial scan complete. Ready for changes'))
     .on('raw', (event, path, details) => { // internal
      log('Raw event info:', event, path, details);
     });
    이상은 노드입니다.js가 파일 변화를 어떻게 감시하는지에 대한 상세한 내용,node에 대한 자세한 내용.js 감시 파일의 자료는 우리의 다른 관련 문장을 주목하세요!

    좋은 웹페이지 즐겨찾기