Node.js:确定修改时的文件大小 [英] Node.js: Determine file size on modification

查看:156
本文介绍了Node.js:确定修改时的文件大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看Node.js中的一个文件,并希望在每次更改时都获取文件的大小。这怎么可以用 fs.watchFile



完成这是我现在正在做的:

  fs.watchFile(file,function(curr,prev){
//确定文件大小
});


解决方案

我错过了 fs.watchFile 返回的< C> fs.Stats 。这将是最佳的解决方案:

  var fs = require('fs'); 

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

但是,从Node v0.8.0开始, fs.watchFile 不再使用 IOWatcher ,现在使用stat轮询,这很慢并且不提供实时更新。这已在 GitHub 上讨论。



从节点更新日志


弃用iowatcher,fs:fix fs.watchFile()(Ben Noordhuis)

现在 fs.watch fs.stat

  var fs = require('fs'); 
$ b fs.watch('file',function(curr,prev){
fs.stat('file',function(err,stats){
console.log stats.size);
});
});


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?

This is what I'm currently doing:

fs.watchFile(file, function(curr, prev) {
  // determine file size
});

解决方案

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:

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.

From the Node changelog:

Deprecate iowatcher, fs: fix fs.watchFile() (Ben Noordhuis)

Instead, an alternate solution is now fs.watch and fs.stat:

var fs = require('fs');

fs.watch('file', function (curr, prev) {
  fs.stat('file', function (err, stats) {
    console.log(stats.size);
  });
});

这篇关于Node.js:确定修改时的文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆