需要实现的功能是监控rules目录内的文件是否发生了变化,如果发生变化自动重新解析。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| var fs = require('fs'); var rc = require('./rulesConf'); rc.getRulesConf(parseNext);
watchRuleFileChange('./rules/');
function parseNext(result) { console.log('parse next-------'); console.log(JSON.stringify(result)); }
function watchRuleDirChange(ruleDir){ console.log('watching :'+ruleDir); fs.watch(ruleDir,{persistent: true, recursive: false},function(event, filename){ console.log('watching: '+filename +' '+event); rc.getRulesConf(parseNext); }); }
function watchRuleFileChange(ruleDir){ console.log('watching :'+ruleDir); fs.readdir(ruleDir,function(error,files){ files.forEach(function(file){ watchFileChange(ruleDir+file); }); }); }
function watchFileChange(filename){ fs.watchFile(filename, {persistent: true, interval: 5000}, function(curr,prev){ if(curr.mtime > prev.mtime){ console.log("curr.mtime:"+curr.mtime+" prev.mtime:"+prev.mtime); rc.getRulesConf(parseNext); } } ); }
|