perhaps? 2011-05-27 18:49 采纳率: 100%
浏览 881
已采纳

在 node.js 中每次读取一行文件?

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.

转载于:https://stackoverflow.com/questions/6156501/read-a-file-one-line-at-a-time-in-node-js

  • 写回答

25条回答 默认 最新

  • 关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(24条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站