2017-03-13 15:28:51 -04:00
|
|
|
'use strict';
|
2019-02-05 20:59:09 -05:00
|
|
|
const fsExtra = require('fs-extra');
|
|
|
|
const Promise = require('bluebird');
|
|
|
|
const readline = require('readline');
|
2017-03-13 15:28:51 -04:00
|
|
|
|
|
|
|
module.exports = readLines;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Read a file line-by-line.
|
|
|
|
*
|
|
|
|
* @param {String} path Path to the file.
|
|
|
|
* @param {Function} callback Function to call when reading each line.
|
|
|
|
* @returns {Promise} A promise when the reader is finished.
|
|
|
|
*
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
function readLines(path, callback) {
|
2017-07-29 13:23:33 -04:00
|
|
|
return new Promise(function(resolve, reject) {
|
2019-02-05 20:59:09 -05:00
|
|
|
const stream = fsExtra.createReadStream(path);
|
2017-06-28 13:15:56 -04:00
|
|
|
stream.on('error', reject);
|
|
|
|
stream.on('end', resolve);
|
|
|
|
|
2019-02-05 20:59:09 -05:00
|
|
|
const lineReader = readline.createInterface({
|
2017-07-29 13:23:33 -04:00
|
|
|
input : stream
|
2017-06-28 13:15:56 -04:00
|
|
|
});
|
2019-10-27 15:26:40 -04:00
|
|
|
|
2019-10-27 15:00:35 -04:00
|
|
|
const callbackWrapper = function(line) {
|
|
|
|
try {
|
|
|
|
callback(line);
|
|
|
|
} catch (error) {
|
|
|
|
reject(error);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
lineReader.on('line', callbackWrapper);
|
2017-03-13 15:28:51 -04:00
|
|
|
});
|
|
|
|
}
|