[英]Node.js: Determine file size on modification
I'm watching a file in Node.js and would like to obtain the size of the file each time it changes. 我正在观看Node.js中的文件,并希望每次更改时获取文件的大小。 How can this be done with
fs.watchFile
? 如何用
fs.watchFile
完成这项工作?
This is what I'm currently doing: 这就是我目前正在做的事情:
fs.watchFile(file, function(curr, prev) {
// determine file size
});
var fs = require('fs');
fs.watchFile('some.file', function () {
fs.stat('some.file', function (err, stats) {
console.log(stats.size);
});
});
I missed that the variables curr
and prev
that were returned from fs.watchFile
were instances of fs.Stats
. 我错过了从
fs.watchFile
返回的变量curr
和prev
是fs.Stats
实例。 This would be the optimal solution: 这将是最佳解决方案:
var fs = require('fs');
fs.watchFile('file', function (curr, prev) {
console.log(curr.size);
});
However, as of Node v0.8.0, fs.watchFile
no longer uses IOWatcher
, and now uses stat polling, which is slow and does not provide realtime updates. 但是,从Node v0.8.0开始,
fs.watchFile
不再使用IOWatcher
,现在使用stat轮询,这很慢并且不提供实时更新。 This was discussed on GitHub . 这在GitHub上进行了讨论。
From the Node changelog : 从节点更改日志 :
Deprecate iowatcher, fs: fix fs.watchFile() (Ben Noordhuis)
弃用iowatcher,fs:fix fs.watchFile()(Ben Noordhuis)
Instead, an alternate solution is now fs.watch
and fs.stat
: 相反,另一种解决方案现在是
fs.watch
和fs.stat
:
var fs = require('fs');
fs.watch('file', function (curr, prev) {
fs.stat('file', function (err, stats) {
console.log(stats.size);
});
});
使用fs.stat
回调: watchFile
只是让你知道它改变了,它不报告的变化细节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.