rcreddy
rcreddy

Reputation: 95

how to Read the File untill last line and wait for data to be availbale in Nodejs

I have requirement where I need parse all the lines of the text file until the last line, and to wait for the Data to be available in a text file (contents of the file are filepaths in each line) I have written the node js code as follows utilizing the readStream,Readable.resume(),Readable.pause()


const fs = require('fs');

const filename = "C:\\Temp\\removeme.txt";

var watching = false;

var readStream = fs.createReadStream(filename);

readStream.on('data', data => {
    console.log(data.toString());
    if(watching) readStream.pause();
});

watching = true;

fs.watch(filename,{persistent: true}, (event,file_name) => {
    if(event === 'change') {
        readStream.resume();
    }
});

However, once the watch is started, I can get the events whenever I update the file using echo "Test String" >> C:\Temp\removeme.txt but not the data event on readStream. I tried diffirent ways without any success. Any help/pointers is greatly appreciated

Upvotes: 1

Views: 526

Answers (1)

Rob Raisch
Rob Raisch

Reputation: 17357

As they say: "There's a module for that!"

See file-tail

In future, I find npm to be an invaluable resource for finding modules! Select two or three words that best describe what you're looking for and use them in the npm search command, as in:

$> npm search file tail

which produces:

NAME | DESCRIPTION | AUTHOR | DATE | VERSION | KEYWORDS
read-chunk | Read a chunk from a… | =sindresorhus | 2017-07-30 | 2.1.0 | read file readfile fs chunk slice part head tail buffer fd open tail | tail a file in node | =lucagrulla | 2017-10-22 | 1.2.3 | tail file fs-tail-stream | fs.createReadStream… | =eugeneware | 2017-02-02 | 1.1.0 | fs createReadStream tail tailing watch watching ... ...

Or submit your words to the search bar at npmjs.

Upvotes: 1

Related Questions