This is a problem I once had, and it was quite a headache. This is the implementation that I came up with.
var fs = require('fs');
var file = __dirname + '/file.log';
fs.stat(file, function(err, stats) {
var start = stats.size;
// read the entire file here if you need it
watchFile(start);
});
function watchFile(start) {
fs.watch(file, function(event, filename) {
fs.stat(file, function(err, stats) {
var stream = fs.createReadStream(file, {
start: start,
end: stats.size
});
var lines = new String();
stream.on('data', function(data) {
lines += data;
});
stream.on('end', function() {
// you have the new lines
});
start = stats.size + 1;
});
});
};
First I find the size of the file, and pass it to a watch function. Every time the file changes, I find out the new size of the file and read from the old position to the new position. On some systems the watch function might fire twice per change, so you might want to add checks to get rid of useless reads such as when the start and end are the same byte.