Reputation: 55
I want to read a text file line by line with nodejs. This works fine with a readable stream. The problem is a other program adds lines to the file. I just want to read the new lines or changes and not the hole file. I Tried it with the functions to move the cursor. But this works only with a writable stream. Is there a possibility to resume the stream after the 'end' event occurs? Or how I can read just a few lines at a specific position of a File?
var readableStream = fs.createReadStream('file.txt');
var data = '';
readableStream.on('data', function(chunk) {
data+=chunk;
});
readableStream.on('end', function() {
console.log(data);
});
It work also fine with the readline core module. But how I can read a single line from a file.
Upvotes: 3
Views: 1394
Reputation: 554
My way of doing this would be to save the last position and skip those bytes on the next read with stream-skip
Upvotes: 0
Reputation: 30739
The filestream library has a watch
function which you can use to watch changes in a file. The function executes when there are changes in the file either from nodejs or from external source.
fs.watch('pathToDirectory', function (event, filename) {
console.log('event is: ' + event);
if (filename) {
console.log('filename provided: ' + filename);
} else {
console.log('filename not provided');
}
});
You can read further fs.watch() to know more about this. This is what you should use to achieve what you are asking.
Upvotes: 2