在NodeJS中读取文件的第N行 [英] Read Nth line of file in NodeJS

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

问题描述

鉴于我知道路径名和行号,因此我尝试提取文件的单行,理想情况下,我想这样做而无需读取多余的文件 strong>.

I'm attempting to extract a single line of a file, given that I know the pathname and the line number, ideally I'd like to do this without reading any more of the file than is necessary.

出于我在这里使用的目的,这是异步还是同步都没关系.

For the purpose I'm using here, it doesn't matter if this is async or sync.

我当前的(不好的)实现看起来像这样:

My current (bad) implementation looks like this:

function get_line(filename, line_no, callback) {
    line_no = parseInt(line_no);
    var data = fs.readFileSync(filename, 'utf8');
    var lines = data.split("\n");
    for (var l in lines) {
        if (l == line_no - 1) {
            callback(null, lines[l].trim());
            return;
        }
    }
    throw new Error('File end reached without finding line');
}

我尝试使用createReadStream进行操作,但是数据事件似乎从未触发.谁能提供直接解决此问题的方法,或者向我介绍一些NodeJS文件系统交互文档,该文档比标准库API文档驱动的示例更多?

I tried to do something with a createReadStream, but the data events never seemed to fire. Can anyone provide a direct solution to this problem, or point me towards some NodeJS filesystem interaction documentation that is a little more example driven than the standard library API docs?

推荐答案

具有可读流

var fs = require('fs');

function get_line(filename, line_no, callback) {
    var stream = fs.createReadStream(filename, {
      flags: 'r',
      encoding: 'utf-8',
      fd: null,
      mode: 0666,
      bufferSize: 64 * 1024
    });

    var fileData = '';
    stream.on('data', function(data){
      fileData += data;

      // The next lines should be improved
      var lines = fileData.split("\n");

      if(lines.length >= +line_no){
        stream.destroy();
        callback(null, lines[+line_no]);
      }
    });

    stream.on('error', function(){
      callback('Error', null);
    });

    stream.on('end', function(){
      callback('File end reached without finding line', null);
    });

}

get_line('./file.txt', 1, function(err, line){
  console.log('The line: ' + line);
})

直接解决方案:

您应该使用slice方法而不是循环.

You should use the slice method instead of a loop.

var fs = require('fs');

function get_line(filename, line_no, callback) {
    var data = fs.readFileSync(filename, 'utf8');
    var lines = data.split("\n");

    if(+line_no > lines.length){
      throw new Error('File end reached without finding line');
    }

    callback(null, lines[+line_no]);
}

get_line('./file.txt', 9, function(err, line){
  console.log('The line: ' + line);
})

for(行中的var l)不是循环遍历数组的最有效方法,您应该这样做:

for (var l in lines) isn't the most efficient way for looping over an array, you should do this instead:

for(var i = 0, iMax = lines.length; i < iMax; i++){/* lines[i] */ }

异步方式:

var fs = require('fs');

function get_line(filename, line_no, callback) {
    fs.readFile(filename, function (err, data) {
      if (err) throw err;

      // Data is a buffer that we need to convert to a string
      // Improvement: loop over the buffer and stop when the line is reached
      var lines = data.toString('utf-8').split("\n");

      if(+line_no > lines.length){
        return callback('File end reached without finding line', null);
      }

      callback(null, lines[+line_no]);
    });
}

get_line('./file.txt', 9, function(err, line){
  console.log('The line: ' + line);
})

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

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