如何用Regex和Chokidar检测文件特定内容变化并触发JS函数
实现文件特定内容变化触发JS函数的方案
- 用Chokidar监听文件变化,同时维护文件的历史内容快照,每次触发变化事件时,读取当前文件内容,对比指定正则匹配的部分是否有变更。
具体实现步骤
- 初始化Chokidar并维护历史快照
先在监听前读取一次文件内容,作为初始快照。之后每次文件变化时,读取新内容,和快照对比。const chokidar = require('chokidar'); const fs = require('fs').promises; const path = require('path'); // 要监控的文件路径 const targetFile = path.resolve('./target.txt'); // 用于匹配特定内容的正则 const watchRegex = /^\[config\].*?(?=\n\[|$)/ms; // 存储历史内容快照 let lastMatchedContent = ''; // 初始化读取初始内容 async function initSnapshot() { const content = await fs.readFile(targetFile, 'utf8'); const match = content.match(watchRegex); lastMatchedContent = match ? match[0] : ''; } initSnapshot().then(() => { // 启动监听 const watcher = chokidar.watch(targetFile, { persistent: true }); watcher.on('change', async () => { try { const currentContent = await fs.readFile(targetFile, 'utf8'); const currentMatch = currentContent.match(watchRegex); const currentMatchedContent = currentMatch ? currentMatch[0] : ''; // 对比正则匹配的部分是否有变化 if (currentMatchedContent !== lastMatchedContent) { // 运行你的目标函数 runYourFunction(currentMatchedContent, lastMatchedContent); // 更新快照 lastMatchedContent = currentMatchedContent; } } catch (err) { console.error('读取文件或对比内容出错:', err); } }); }); // 你的目标函数 function runYourFunction(newContent, oldContent) { console.log('监控的内容发生变化了!'); console.log('旧内容:', oldContent); console.log('新内容:', newContent); // 这里写你的业务逻辑 } - 关键细节说明
- 正则要根据你的需求调整,比如上面的例子是匹配
[config]开头到下一个[或文件结尾的块。 - 使用
fs.promises异步读取文件,避免阻塞事件循环。 - 只有当正则匹配的部分真的变化时,才触发目标函数,避免文件其他部分修改导致误触发。
- 异常处理要加上,防止文件读取失败导致监听逻辑崩溃。
- 正则要根据你的需求调整,比如上面的例子是匹配
优化建议
- 如果监控的文件很大,可以考虑只读取文件的部分内容,或者用增量对比的方式提升性能,但简单场景下全量读取对比足够用。
- 可以把历史快照存在本地文件里,避免进程重启后丢失初始状态。
内容的提问来源于stack exchange,提问作者Felix Ranesberger
相关产品推荐
相关产品推荐

