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.
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.
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');
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); });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With