DEV Community

Cover image for Node.js : Reading a file line by line
Rajesh Kumar Yadav
Rajesh Kumar Yadav Subscriber

Posted on • Edited on

Node.js : Reading a file line by line

Create a file as app.js (or whatever name you want) and paste below code -

app.js

const readline = require('readline');
const fs = require('fs');
var file = 'path.to.file';
var rl = readline.createInterface({
 input: fs.createReadStream(file),
 output: process.stdout,
 terminal: false
});
rl.on('line', function (line) {
 console.log(line) // print the content of the line on each linebreak
});
Enter fullscreen mode Exit fullscreen mode

path.to.file will be path of your file and once modified this line you can run 'node app.js' and you will get the file reading as line by line.

Buy Me A Coffee

With all that being said, I highly recommend you keep learning!

Thank you for reading this article. Please feel free to connect with me on LinkedIn and Twitter.

Top comments (1)

Collapse
 
pankajkb profile image
Pankaj Bhadane

how can i read random line from file ? any modification to this code ?