ChevCast
ChevCast

Reputation: 59163

In a node script how can I monitor a file for changes and get the updated content?

I'm writing a script to monitor a file. Whenever the file changes it needs to print to the appended content to the console. I'm dabbling with fs.createReadStream but it doesn't seem to send anymore data over the stream when the file is appended to. I'm also just plain new to streams in general. Hopefully I just need someone to point me in the right direction :)

Upvotes: 1

Views: 232

Answers (1)

Paul
Paul

Reputation: 141829

You can use the node-watch module:

var watch = require('node-watch');

watch('somedir_or_somefile', function(filename) {
    console.log(filename, ' changed.');
});

If you are operating under the assumption that the file is only being appended to, you could store the number of bytes read so far in a variable, and then inside your watch callback, use that as the position argument for fs.read.

Upvotes: 2

Related Questions