最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js: Determine file size on modification - Stack Overflow

programmeradmin0浏览0评论

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'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
});
Share Improve this question edited Sep 1, 2014 at 1:35 hexacyanide asked Sep 4, 2012 at 6:02 hexacyanidehexacyanide 91.6k31 gold badges165 silver badges162 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 13
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. 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);
  });
});

Use fs.stat in the callback: watchFile just lets you know it changed, it doesn't report the change details.

发布评论

评论列表(0)

  1. 暂无评论