chokidar 与热重载
开发时文件监控。
25 分钟
chokidar 与热重载
开发 CLI 或代码生成器时,希望 源文件变更自动重新执行——chokidar 跨平台监听文件系统,比裸 fs.watch 更稳。本课对应 file watching 与本地 DX,生产 runtime 一般不依赖 watch。
学习目标
- 用 chokidar 监听目录与 glob 模式
- 实现 debounce,避免保存风暴触发多次构建
- 理解 watch 与 nva-glob 的组合
基本监听
import chokidar from "chokidar";
const watcher = chokidar.watch("src/**/*.md", {
ignored: /(^|[/\\])\../,
persistent: true,
});
watcher
.on("add", (path) => console.log("add", path))
.on("change", (path) => console.log("change", path))
.on("unlink", (path) => console.log("unlink", path));
ignored 排除 .git、 node_modules;大仓库要收窄 glob。
debounce 重跑
let timer;
function scheduleRebuild(reason) {
clearTimeout(timer);
timer = setTimeout(() => {
console.error(`[rebuild] ${reason}`);
// 调用模板编译或 import 预览
}, 300);
}
watcher.on("change", (p) => scheduleRebuild(p));
编辑器一次保存可能触发多个 change 事件;300ms debounce 是常见起点。
与 nodemon / tsx watch 分工
| 工具 | 场景 |
|---|---|
| nodemon | 重启 Node 进程跑入口 |
| tsx --watch | TS 直接执行 + 重启 |
| chokidar | 自定义流水线(生成、lint、同步) |
nest-setup 的 nest start --watch 内置编译监听;内容站点 或 import CLI 的「文件变 → 重新渲染」适合自写 chokidar。
资源与退出
process.on("SIGINT", async () => {
await watcher.close();
process.exit(0);
});
长期 watch 进程要 close watcher,否则 Jest / node-test 可能挂起。
练习
- 监听
drafts/*.md,变更时 stderr 打印字数 - 加 debounce,快速连存只触发一次
- 对比 与 chokidar 在删除文件时的行为(笔记)