javascript Node.js:在修改时确定文件大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12257615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js: Determine file size on modification
提问by hexacyanide
I'm watching a file in Node.js and would like to obtain the size of the file each time it changes. How can this be done with fs.watchFile
?
我正在观察 Node.js 中的一个文件,并希望在每次更改时获取该文件的大小。如何做到这一点fs.watchFile
?
This is what I'm currently doing:
这就是我目前正在做的事情:
fs.watchFile(file, function(curr, prev) {
// determine file size
});
回答by Vadim Baryshev
var fs = require('fs');
fs.watchFile('some.file', function () {
fs.stat('some.file', function (err, stats) {
console.log(stats.size);
});
});
回答by hexacyanide
I missed that the variables curr
and prev
that were returned from fs.watchFile
were instances of fs.Stats
. This would be the optimal solution:
我错过了变量curr
和prev
返回的变量fs.watchFile
是fs.Stats
. 这将是最佳解决方案:
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. This was discussed on GitHub.
但是,从 Node v0.8.0 开始,fs.watchFile
不再使用IOWatcher
,现在使用 stat 轮询,它很慢并且不提供实时更新。这是在GitHub 上讨论的。
From the Node changelog:
从节点更改日志:
Deprecate iowatcher, fs: fix fs.watchFile() (Ben Noordhuis)
弃用 iowatcher,fs:修复 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);
});
});
回答by Femi
Use fs.stat
in the callback: watchFile
just lets you know it changed, it doesn't report the change details.
fs.stat
在回调中使用:watchFile
只是让您知道它已更改,它不会报告更改详细信息。