node.js 파일 변화 감시 방법
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
rename
및 change
대부분의 플랫폼에서 파일이 디렉터리에 나타나거나 사라질 때'rename'이벤트를 터치하고, Windows에서는 감시하는 디렉터리가 이동하거나 이름을 바꾸면 아무런 이벤트도 터치하지 않으며, 감시하는 디렉터리가 삭제되면 보고EPERM
오류
fs.watch('./', { recursive: true }, (eventType, filename) => {
console.log(eventType, filename);
});
fs.watchFile()fs.watchFile(filename[, options], listener)
파일 변경 모니터링1.filename
2.options
파일을 수정할 때 알림을 받으려면 비교
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()는 운영체제의 실현에 의존하여 서로 다른 플랫폼에서 나타나는 차이가 있다
fs.unwatchFile
interval
filename의 변화를 감시하지 마십시오.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
일상적인 파일 변화 감시에서 지역사회의 우수한 방안을 선택할 수 있다
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 감시 파일의 자료는 우리의 다른 관련 문장을 주목하세요!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Express + AWS S3 이미지 업로드하기웹 사이트 및 모바일 애플리케이션 등에서 원하는 양의 데이터를 저장하고 보호할 수 있다. 데이터에 대한 액세스를 최적화, 구조화 및 구성할 수 있는 관리 기능을 제공한다. AWS S3 에 저장된 객체에 대한 컨테이너...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.