gpt4 book ai didi

javascript - 在 Node.JS 中一次读取一个大文件 N 行

转载 作者:行者123 更新时间:2023-11-30 15:09:56 25 4
gpt4 key购买 nike

我有一个包含 65,000,000 行的文件,大小约为 2GB。

我想一次读取 N 行这个文件,执行数据库插入操作,然后读取下 N 行,在这种情况下,N 为 1000。插入顺序无关紧要,所以同步就可以了。

执行此操作的最佳方法是什么?我只发现要么一次加载 1 行,要么将整个文件读入内存的方法。下面的示例代码,我一直用来一次一行地读取文件。 :

var singleFileParser = (file, insertIntoDB) => {
var lr = new LineByLineReader(file);
lr.on('error', function(err) {
// 'err' contains error object
console.error(err);
console.error("Error reading file!");
});

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

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

最佳答案

某人一次只能解析一行。因此,如果您一次想要 10 个,那么您只需一次收集一个,直到收集到 10 个,然后处理这 10 个。

我不认为 Jarek 的代码能正常工作,所以这里有一个不同的版本,它将 10 行收集到一个数组中,然后调用 dbInsert():

var tenLines = [];
lr.on('line', function(line) {
tenLines.push(line);
if (tenLines.length === 10) {
lr.pause();
dbInsert(<yourSQL>, function(error, returnVal){
if (error) {
// some sort of error handling here
}
tenLines = [];
lr.resume();
});
}
});
// process last set of lines in the tenLines buffer (if any)
lr.on('end', function() {
if (tenLines.length !== 0) {
// process last set of lines
dbInsert(...);
}
});

Jarek 的版本似乎在每个 line 事件上调用 dbInsert() 而不是仅在第 10 行事件上调用,并且不处理文件末尾的任何剩余行如果它们不是 10 行的完美倍数。

关于javascript - 在 Node.JS 中一次读取一个大文件 N 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45260002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com