Skip to content

Instantly share code, notes, and snippets.

@arifmahmudrana
Created November 17, 2019 15:43
Show Gist options
  • Save arifmahmudrana/1ff211b7d93dd50a28cd3b1ac0187904 to your computer and use it in GitHub Desktop.
Save arifmahmudrana/1ff211b7d93dd50a28cd3b1ac0187904 to your computer and use it in GitHub Desktop.
Read a file line by in node.js
const fs = require('fs'); // file system package
const rl = require('readline'); // readline package helps reading data line by line
// create an interface to read the file
const rI = rl.createInterface({
input: fs.createReadStream('/path/to/file') // your path to file
});
rI.on('line', line => {
console.log(line); // your line
});
const getFileContent = path =>
new Promise((resolve, reject) => {
const lines = [],
input = fs.createReadStream(path);
// handle if cann't create a read strem e.g if file not found
input.on('error', e => {
reject(e);
});
// create a readline interface so that we can read line by line
const rI = rl.createInterface({
input
});
// listen to event line when a line is read
rI.on('line', line => {
lines.push(line);
})
// if file read done
.on('close', () => {
resolve(lines);
})
// if any errors occur while reading line
.on('error', e => {
reject(e);
});
});
getFileContent('YOUR_PATH_TO_FILE')
.then(lines => {
console.log(lines);
})
.catch(e => {
console.log(e);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment