我想把一个非常非常大的文件读入node。js中的JavaScript数组。

所以,如果文件是这样的:

first line
two 
three
...
...

我有一个数组:

['first line','two','three', ... , ... ] 

函数看起来是这样的:

var array = load(filename); 

因此,将其全部作为字符串加载,然后将其拆分的想法是不可接受的。


当前回答

使用Node.js的readline模块。

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

var filename = process.argv[2];
readline.createInterface({
    input: fs.createReadStream(filename),
    terminal: false
}).on('line', function(line) {
   console.log('Line: ' + line);
});

其他回答

为了将每行作为数组中的一项,在Node.js v18.11.0中添加了一个逐行读取文件的新函数

filehandle.readLines([选项])

这就是如何将此用于文本文件,您希望读取文件并将每行放入数组中

import { open } from 'node:fs/promises';
const arr = [];
myFilereader();
async function myFileReader() {
    const file = await open('./TextFileName.txt');
    for await (const line of file.readLines()) {
        arr.push(line);
    }
    console.log(arr)
}

为了了解更多read Node.js文档,这里有文件系统readlines()的链接: https://nodejs.org/api/fs.html#filehandlereadlinesoptions

同步:

var fs = require('fs');
var array = fs.readFileSync('file.txt').toString().split("\n");
for(i in array) {
    console.log(array[i]);
}

异步:

var fs = require('fs');
fs.readFile('file.txt', function(err, data) {
    if(err) throw err;
    var array = data.toString().split("\n");
    for(i in array) {
        console.log(array[i]);
    }
});

另一个答案是使用npm包。nexline包允许用户逐行异步读取文件:

"use strict";

import fs from 'fs';
import nexline from 'nexline';

const lines = [];
const reader = nexline({
    input: fs.createReadStream(`path/to/file.ext`)
});

while(true) {
    const line = await reader.next();
    if(line === null) break; // line is null if we reach the end
    if(line.length === 0) continue; // Ignore empty lines
    
    // Process the line here - below is just an example
    lines.push(line);
}

即使您的文本文件大于允许的最大字符串长度,这种方法也可以工作,从而避免“错误:不能创建超过0x1fffffe8个字符的字符串”错误。

文件。行与我的JFile包

var JFile=require('jfile');

var myF=new JFile("./data.txt");
myF.lines // ["first line","second line"] ....

不要忘记之前:

npm install jfile --save

我有同样的问题,我已经解决了它与模块逐行

https://www.npmjs.com/package/line-by-line

至少对我来说,无论是在同步模式还是异步模式下,它都很有魅力。

同样,行终止不终止\n的问题可以用选项解决:

{ encoding: 'utf8', skipEmptyLines: false }

行同步处理:

var LineByLineReader = require('line-by-line'),
    lr = new LineByLineReader('big_file.txt');

lr.on('error', function (err) {
    // 'err' contains error object
});

lr.on('line', function (line) {
    // 'line' contains the current line without the trailing newline character.
});

lr.on('end', function () {
    // All lines are read, file is closed now.
});