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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:43:38  来源:igfitidea点击:

Node.js: Determine file size on modification

javascriptnode.jsfilesystems

提问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 currand prevthat were returned from fs.watchFilewere instances of fs.Stats. This would be the optimal solution:

我错过了变量currprev返回的变量fs.watchFilefs.Stats. 这将是最佳解决方案:

var fs = require('fs');

fs.watchFile('file', function (curr, prev) {
  console.log(curr.size);
});

However, as of Node v0.8.0, fs.watchFileno 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.watchand fs.stat:

相反,另一种解决方案是现在fs.watchfs.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.statin the callback: watchFilejust lets you know it changed, it doesn't report the change details.

fs.stat在回调中使用:watchFile只是让您知道它已更改,它不会报告更改详细信息。