[英]Detect file content changes from node.js
I have a simple file watcher build with chokidar
我有一个简单的文件观察器构建与
chokidar
require('chokidar').watch('./target.txt', {}).on('all', function(event, path) {
console.log(event, path);
}).on('ready', function() {
console.log('ready');
});
It causes change
event every time when I re-save file even without changes. 每次重新保存文件时都会导致
change
事件,即使没有更改也是如此。 Is there a way to make this fire events only if actual content has been changed? 有没有办法只在实际内容发生变化时制作此火灾事件?
You can use the stats
parameter delivered on add
and change
. 您可以使用
add
和change
提供的stats
参数。 This will only work for changes on the size of the file, which should be enough for the vast majority of cases. 这仅适用于文件大小的更改,对于绝大多数情况来说应该足够了。
var watchSize = 0;
require('chokidar').watch('./target.txt', {}).on('all', function(event, path, stats) {
if(stats && stats.size != watchSize) {
watchSize = stats.size;
console.log(event);
}
}).on('ready', function(path, stats) {
console.log('ready');
});
If the few remaining situations are indeed relevant for your case and you have no performance concerns, you can use something like this (following the suggestion in the comments): 如果剩下的几个情况确实与您的情况相关并且您没有性能问题,您可以使用类似的东西(遵循评论中的建议):
var crypto = require("crypto");
var fs = require("fs");
var chokidar = require("chokidar");
watchFile("./target.txt");
//----------------------------------------------------
function watchFile(filePath){
var watchHash;
chokidar.watch(filePath, {}).on("all", function(event, path, stats) {
if (event == "add" || event == "change"){
getHash(filePath, function(hash){
if (hash != watchHash){
watchHash = hash;
console.log(event);
}
});
}
});
}
//----------------------------------------------------
function getHash(filePath, callback){
var stream = fs.ReadStream(filePath);
var md5sum = crypto.createHash("md5");
stream.on("data", function(data) {
md5sum.update(data);
});
stream.on("end", function() {
callback(md5sum.digest("hex"));
});
}
This seems a bit much, though. 但这似乎有点多了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.