node.js:将文本文件读入数组。(每行一个项目在数组中。)

JavaScript Node.js

Itachi猪猪

2020-03-24

我想将非常大的文件读入node.js的JavaScript数组中。

因此,如果文件是这样的:

first line
two 
three
...
...

我将拥有数组:

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

该函数将如下所示:

var array = load(filename); 

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

第3616篇《node.js:将文本文件读入数组。(每行一个项目在数组中。)》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
Eva猿猿 2020.03.24

使用BufferedReader,但函数应该是异步的:

var load = function (file, cb){
    var lines = [];
    new BufferedReader (file, { encoding: "utf8" })
        .on ("error", function (error){
            cb (error, null);
        })
        .on ("line", function (line){
            lines.push (line);
        })
        .on ("end", function (){
            cb (null, lines);
        })
        .read ();
};

load ("file", function (error, lines){
    if (error) return console.log (error);
    console.log (lines);
});

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android