【问题标题】:How To Read Big Files in NodeJS?如何在 NodeJS 中读取大文件?
【发布时间】:2017-10-31 22:19:44
【问题描述】:

我正在尝试读取 2000 万行文件并将行结尾从 windows 更正为 mac。我知道它可以在 sed 中完成,但 sed 给了我一个我不知道如何修复的错误(dos2unix:在第 625060 行找到二进制符号 0x0008)。所以我试图在 NodeJS 中解决这个问题。这是我的代码:

var fs = require('fs');
var eol = require('eol');

//read file
var input = fs.readFileSync(process.argv[2], 'utf8');

//fix lines
output = eol.auto(input);
console.log("Lines Fixed! Now Writing....")

//write file
fs.writeFile(process.argv[2] + '_fixed.txt', output, function (err) {
  if (err) return console.log(err); 
});
console.log("Done!")

问题是文件太大,我得到这个错误 buffer.js:513 throw new Error('"toString()" failed');

【问题讨论】:

标签: node.js sed


【解决方案1】:

您不应该同步进行。 处理大数据的最佳方式是流:

let output = '';

const readStream = fs.createReadStream(filename);

readStream.on('data', function(chunk) {
  output += eol.auto(chunk.toString('utf8'));
});

readStream.on('end', function() {
  console.log('finished reading');
  // write to file here.
});

【讨论】:

  • 什么是 eol.auto?
  • 这是一个用于处理文本npmjs.com/package/eol 的库。方法“auto”规范化行尾。如果你不需要它,你可以简单地删除它。
【解决方案2】:

要读取非常大的文件,最好不要将整个文件读入内存,可以逐行或逐块读取文件。关于如何使用 nodejs 按行或按块读取大文件,请参阅我的 answer here node.js: read a text file into an array. (Each line an item in the array.)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 2018-01-19
    • 2016-04-17
    • 1970-01-01
    • 2021-05-23
    • 2022-06-14
    相关资源
    最近更新 更多