Friday 12 January 2018

javascript - Read a file one line at a time in node.js?

itemprop="text">

I am trying to read a large file one
line at a time. I found href="http://www.quora.com/What-is-the-best-way-to-read-a-file-line-by-line-in-node-js"
rel="noreferrer">a question on Quora that dealt with the subject but I'm
missing some connections to make the whole thing fit
together.



 var
Lazy=require("lazy");
new Lazy(process.stdin)
.lines

.forEach(
function(line) {
console.log(line.toString());


}
);

process.stdin.resume();


The
bit that I'd like to figure out is how I might read one line at a time from a file
instead of STDIN as in this sample.



I tried:



 fs.open('./VeryBigFile.csv',
'r', '0666', Process);


function Process(err, fd)
{
if (err) throw err;
// DO lazy read

}


but it's not
working. I know that in a pinch I could fall back to using something like PHP, but I
would like to figure this out.



I don't think
the other answer would work as the file is much larger than the server I'm running it on
has memory for.



itemprop="text">
class="normal">Answer



Since
Node.js v0.12 and as of Node.js v4.0.0, there is a stable href="https://nodejs.org/api/readline.html" rel="noreferrer">readline core
module. Here's the easiest way to read lines from a file, without any external
modules:



var lineReader =
require('readline').createInterface({
input:
require('fs').createReadStream('file.in')
});

lineReader.on('line',
function (line) {
console.log('Line from file:',
line);
});



The
last line is read correctly (as of Node v0.12 or later), even if there is no final
\n.



UPDATE:
this example has been href="https://nodejs.org/api/readline.html#readline_example_read_file_stream_line_by_line"
rel="noreferrer">added to Node's API official
documentation.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...