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
var fs = require('fs');
fs.watchFile('some.file', function () {
fs.stat('some.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.
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);
});
});