在node.js中一次读取一行文件? [英] Read a file one line at a time in node.js?

查看:106
本文介绍了在node.js中一次读取一行文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图一次读一行大文件。我发现一个关于Quora的问题,处理这个问题,但我错过了一些连接,使整个事情合适。

  var Lazy = require(lazy); 
new Lazy(process.stdin)
.lines
.forEach(
function(line){
console.log(line.toString());
}
);
process.stdin.resume();

我想知道的是,我可能会一次读一行一个文件,而不是STDIN,因为在这个例子中。

我试过:

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

函数进程(err,fd){
if(err)throw err;
// DO懒读
}

但是不起作用。我知道,在一个捏,我可以退回到使用PHP的东西,但我想弄清楚这一点。



我不认为其他答案是可行的,因为这个文件比我运行内存的服务器大得多。由于Node.js v0.12和Node.js v4.0.0一样,有一个稳定的读线核心模块。这里是从文件中读取行的最简单的方法,没有任何外部模块:

  var lineReader = require('readline')。 createInterface({
input:require('fs')。createReadStream('file.in')
});
$ b lineReader.on('line',function(line){
console.log('Line from file:',line);
});

最后一行读取正确(从v0.12或更高版本开始),即使存在没有最后 \\\



更新:这个例子已经添加到Node的API官方文档

I am trying to read a large file one line at a time. I found 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.

解决方案

Since Node.js v0.12 and as of Node.js v4.0.0, there is a stable 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 added to Node's API official documentation.

这篇关于在node.js中一次读取一行文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆