Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

watch file for new content and retrieve that content in NodeJS

Tags:

I am monitoring the file for content change using Node.js watch File. Its succesfully calling the event when content of the file is modified

fs.watchFile(filePath, ()=> {
    console.log('File Changed ...');
    file = fs.readFileSync(filePath);
    console.log('File content at : ' + new Date() + ' is \n' + file);
});

from Hello to Hello World

I want only the World not all the contents of the file, can any one suggest the most efficient way to achieve this or any node package to achieve this. I looked at node package Chokidar but that also monitors the change.

I found a JAVA Solution for that, but not sure of any Node.js alternative for that.

How to watch file for new content and retrieve that content

I did my research tried to follow these posts

https://nodejs.org/api/fs.html#fs_fs_watchfile_filename_options_listener

http://www.codingdefined.com/2015/09/how-to-monitor-file-for-modifications.html

Observe file changes with node.js

Thanks

like image 888
Akash Avatar asked Jan 27 '17 05:01

Akash


1 Answers

The best way to do it is by creating a stream that reads the file and remains open for file changes. I found this tool that describes and solves this problem:

tailing-stream is a Node.js module that provides a Stream that can read continuously from a file that's being actively written to. This is in contrast to the standard fs.createReadStream. method, which returns a ReadableStream that stops reading once it gets to the last byte that existed at the time the stream was originally opened. It supports exactly the same interface as a Node ReadableStream, and its createReadStream method functions the same as fs.createReadStream.

https://github.com/jasontbradshaw/tailing-stream

You can install it using npm:

npm install tailing-stream

And here's a simple example:

const fs = require('fs');
const TailingReadableStream = require('tailing-stream');

const stream = TailingReadableStream.createReadStream("file", {timeout: 0});

stream.on('data', buffer => {
  console.log(buffer.toString());
});
stream.on('close', () => {
  console.log("close");
});
like image 137
Hugo Aboud Avatar answered Sep 25 '22 10:09

Hugo Aboud