Created
January 8, 2019 11:29
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| '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