Node.js: determining file size during modification

I am looking at a file in Node.js and want to get the file size every time it changes. How can this be done with fs.watchFile ?

This is what I am doing now:

 fs.watchFile(file, function(curr, prev) { // determine file size }); 
+4
source share
3 answers

I skipped that the curr and prev variables that were returned from fs.watchFile were instances of fs.Stats . This would be the best solution:

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

However, starting with Node v0.8.0, fs.watchFile no longer uses IOWatcher , and now uses statistics polling, which is slow and does not provide real-time updates. This has been discussed on GitHub .

From Node changelog :

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

Instead, an alternative 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); }); }); 
+6
source
 var fs = require('fs'); fs.watchFile('some.file', function () { fs.stat('some.file', function (err, stats) { console.log(stats.size); }); }); 
+13
source

Use fs.stat in the callback: watchFile just lets you know that it is changed, it does not report the change data.

+2
source

Source: https://habr.com/ru/post/1432198/


All Articles