function eachLine(filename, options, iteratee, cb) { if (options instanceof Function) { cb = iteratee; iteratee = options; options = undefined; } var asyncIteratee = iteratee.length === 3; var theReader; var getReaderCb; open(filename, options, function(err, reader) { theReader = reader; if (getReaderCb) { getReaderCb(reader); } if (err) { if (cb) cb(err); return; } function finish(err) { reader.close(function(err2) { if (cb) cb(err || err2); }); } function newRead() { if (reader.hasNextLine()) { setImmediate(readNext); } else { finish(); } } function continueCb(continueReading) { if (continueReading !== false) { newRead(); } else { finish(); } } function readNext() { reader.nextLine(function(err, line) { if (err) { finish(err); } var last = !reader.hasNextLine(); if (asyncIteratee) { iteratee(line, last, continueCb); } else { if (iteratee(line, last) !== false) { newRead(); } else { finish(); } } }); } newRead(); }); // this hook is only for the sake of testing; if you choose to use it, // please don't file any issues (unless you can also reproduce them without // using this). return { getReader: function(cb) { if (theReader) { cb(theReader); } else { getReaderCb = cb; } } }; }
...
The `eachLine` function reads each line of the given file. Upon each new line,
the given callback function is called with two parameters: the line read and a
boolean value specifying whether the line read was the last line of the file.
If the callback returns `false`, reading will stop and the file will be closed.
var lineReader = require('line-reader');
lineReader.eachLine('file.txt', function(line, last) {
console.log(line);
if (/* done */) {
return false; // stop reading
}
});
...
function open(filenameOrStream, options, cb) { if (options instanceof Function) { cb = options; options = undefined; } var readStream; if (typeof filenameOrStream.read == 'function') { readStream = filenameOrStream; } else if (typeof filenameOrStream === 'string' || filenameOrStream instanceof String) { readStream = fs.createReadStream(filenameOrStream); } else { cb(new Error('Invalid file argument for LineReader.open. Must be filename or stream.')); return; } readStream.pause(); createLineReader(readStream, options, cb); }
...
console.log("I'm done!!");
});
For more granular control, `open`, `hasNextLine`, and `nextLine` maybe be used
to iterate a file (but you must `close` it yourself):
// or read line by line:
lineReader.open('file.txt', function(err, reader) {
if (err) throw err;
if (reader.hasNextLine()) {
reader.nextLine(function(err, line) {
try {
if (err) throw err;
console.log(line);
} finally {
...