Node.js: Determine file size on modification

前端 未结 3 1199
深忆病人
深忆病人 2021-01-13 15:11

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

相关标签:
3条回答
  • 2021-01-13 15:47
    var fs = require('fs');
    
    fs.watchFile('some.file', function () {
        fs.stat('some.file', function (err, stats) {
            console.log(stats.size);
        });
    });
    
    0 讨论(0)
  • 2021-01-13 15:54

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

    0 讨论(0)
  • 2021-01-13 15:56

    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);
      });
    });
    
    0 讨论(0)
提交回复
热议问题