admin管理员组文章数量:1421000
I have a simple file watcher build with 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. Is there a way to make this fire events only if actual content has been changed?
I have a simple file watcher build with 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. Is there a way to make this fire events only if actual content has been changed?
1 Answer
Reset to default 6You can use the stats
parameter delivered on add
and change
. 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 ments):
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.
本文标签: javascriptDetect file content changes from nodejsStack Overflow
版权声明:本文标题:javascript - Detect file content changes from node.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745338008a2654132.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论