Skip to content

Instantly share code, notes, and snippets.

@rodrigocfd
Created January 8, 2019 11:29
Show Gist options
  • Select an option

  • Save rodrigocfd/79b4ec70e987ac9b7f0a93ec0a851465 to your computer and use it in GitHub Desktop.

Select an option

Save rodrigocfd/79b4ec70e987ac9b7f0a93ec0a851465 to your computer and use it in GitHub Desktop.
Reads a file line by line and returns a string array in JavaScript and Node.js.
'use strict';
const fs = require('fs');
const readline = require('readline');
function readLines(fileName) {
return new Promise((resolve, reject) => {
if (!fs.existsSync(fileName)) {
return reject('File not found: ' + fileName);
}
let rl = readline.createInterface({
input: fs.createReadStream(fileName),
console: false
});
let lines = [];
rl.on('line', line => lines.push(line));
rl.on('close', () => resolve(lines));
rl.on('error', err => reject(err));
});
}
module.exports = readLines;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment