Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do `tail -f logfile.txt`-like processing in node.js?

Tags:

node.js

tail -f logfile.txt outputs the last 10 lines of logfile.txt, and then continues to output appended data as the file grows.

What's the recommended way of doing the -f part in node.js?

The following outputs the entire file (ignoring the "show the last 10 lines") and then exits.

var fs = require('fs'); var rs = fs.createReadStream('logfile.txt', { flags: 'r', encoding: 'utf8'}); rs.on('data', function(data) {   console.log(data); }); 

I understand the event-loop is exiting because after the stream end & close event there are no more events -- I'm curious about the best way of continuing to monitor the stream.

like image 518
mike Avatar asked Jan 24 '12 20:01

mike


People also ask

How do I read the last 10 lines of a node js file?

var fs = require('fs'); var readline = require('readline'); var stream = require('stream'); var instream = fs. createReadStream('your/file'); var outstream = new stream; var rl = readline. createInterface(instream, outstream); rl. on('line', function(line) { // process line here }); rl.

How do I read a text file line by line in node js?

Method 1: Using the Readline Module: Readline is a native module of Node. js, it was developed specifically for reading the content line by line from any readable stream. It can be used to read data from the command line. const readline = require('readline');


2 Answers

The canonical way to do this is with fs.watchFile.

Alternatively, you could just use the node-tail module, which uses fs.watchFile internally and has already done the work for you. Here is an example of using it straight from the documentation:

Tail = require('tail').Tail;  tail = new Tail("fileToTail");  tail.on("line", function(data) {   console.log(data); }); 
like image 108
Rohan Singh Avatar answered Sep 21 '22 10:09

Rohan Singh


node.js APi documentation on fs.watchFile states:

Stability: 2 - Unstable. Use fs.watch instead, if available.

Funny though that it says almost the exact same thing for fs.watch:

Stability: 2 - Unstable. Not available on all platforms.

In any case, I went ahead and did yet another small webapp, TailGate, that will tail your files using the fs.watch variant.

Feel free to check it out here: TailGate on github.

like image 40
Tackle Avatar answered Sep 18 '22 10:09

Tackle