Bun 은 파일 시스템 변경 사항 리스닝을 위한 fs.watch 함수를 포함한 node:fs 모듈을 구현합니다.
이 코드 블록은 현재 디렉터리의 파일 변경 사항을 리스닝합니다. 기본적으로 이 작업은 얕은 방식으로 하위 디렉터리의 파일 변경 사항은 감지되지 않습니다.
ts
import { watch } from "fs";
const watcher = watch(import.meta.dir, (event, filename) => {
console.log(`${filename} 에서 ${event} 감지됨`);
});하위 디렉터리의 변경 사항을 리스닝하려면 fs.watch 에 recursive: true 옵션을 전달합니다.
ts
import { watch } from "fs";
const watcher = watch(import.meta.dir, { recursive: true }, (event, relativePath) => {
console.log(`${relativePath} 에서 ${event} 감지됨`);
});node:fs/promises 모듈을 사용하면 콜백 대신 for await...of 를 사용하여 변경 사항을 리스닝할 수 있습니다.
ts
import { watch } from "fs/promises";
const watcher = watch(import.meta.dir);
for await (const event of watcher) {
console.log(`${event.filename} 에서 ${event.eventType} 감지됨`);
}변경 사항 리스닝을 중지하려면 watcher.close() 를 호출합니다. 사용자가 Ctrl-C 를 누를 때와 같이 프로세스가 SIGINT 신호를 받을 때 이를 수행하는 것이 일반적입니다.
ts
import { watch } from "fs";
const watcher = watch(import.meta.dir, (event, filename) => {
console.log(`${filename} 에서 ${event} 감지됨`);
});
process.on("SIGINT", () => {
// Ctrl-C 를 누르면 watcher 닫기
console.log("watcher 닫는 중...");
watcher.close();
process.exit(0);
});BunFile 작업에 대한 자세한 내용은 API > 파일 I/O 를 참조하세요.