从 node.js 检测文件内容更改 [英] Detect file content changes from node.js
问题描述
我使用 chokidar
require('chokidar').watch('./target.txt', {}).on('all', function(event, path) {
console.log(event, path);
}).on('ready', function() {
console.log('ready');
});
每次我重新保存文件时,即使没有更改,它也会导致 change
事件.有没有办法仅在实际内容已更改时才触发此事件?
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?
推荐答案
您可以使用 add
和 change
上提供的 stats
参数.这仅适用于文件大小的更改,这对于绝大多数情况来说应该足够了.
You 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 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"));
});
}
不过,这似乎有点多.
这篇关于从 node.js 检测文件内容更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!