我想把一个非常非常大的文件读入node。js中的JavaScript数组。
所以,如果文件是这样的:
first line
two
three
...
...
我有一个数组:
['first line','two','three', ... , ... ]
函数看起来是这样的:
var array = load(filename);
因此,将其全部作为字符串加载,然后将其拆分的想法是不可接受的。
我想把一个非常非常大的文件读入node。js中的JavaScript数组。
所以,如果文件是这样的:
first line
two
three
...
...
我有一个数组:
['first line','two','three', ... , ... ]
函数看起来是这样的:
var array = load(filename);
因此,将其全部作为字符串加载,然后将其拆分的想法是不可接受的。
当前回答
我只是想添加@finbarr伟大的答案,在异步的例子中的一个小修复:
异步:
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]);
}
done();
});
@ madphysics, done()释放async。调用。
其他回答
本质上,这将完成工作:.replace(/\r\n/g,'\n').split('\n')。 这适用于Mac, Linux和Windows。
代码片段
同步:
const { readFileSync } = require('fs');
const array = readFileSync('file.txt').toString().replace(/\r\n/g,'\n').split('\n');
for(let i of array) {
console.log(i);
}
异步:
用fs。promises API提供了另一组异步文件系统方法,返回Promise对象而不是使用回调。(不需要承诺,你也可以使用async-await,在Node.js 10.0.0版本之后可用)
const { readFile } = require('fs').promises;
readFile('file.txt', function(err, data) {
if(err) throw err;
const arr = data.toString().replace(/\r\n/g,'\n').split('\n');
for(let i of arr) {
console.log(i);
}
});
更多关于\r和\n的信息在这里:\r\n, \r和\n它们之间有什么区别?
为了将每行作为数组中的一项,在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'),
es = require('event-stream'),
var lines = [];
var s = fs.createReadStream('filepath')
.pipe(es.split())
.pipe(es.mapSync(function(line) {
//pause the readstream
s.pause();
lines.push(line);
s.resume();
})
.on('error', function(err) {
console.log('Error:', err);
})
.on('end', function() {
console.log('Finish reading.');
console.log(lines);
})
);
一块一块的参考本文
var offset = 0;
var chunkSize = 2048;
var chunkBuffer = new Buffer(chunkSize);
var fp = fs.openSync('filepath', 'r');
var bytesRead = 0;
while(bytesRead = fs.readSync(fp, chunkBuffer, 0, chunkSize, offset)) {
offset += bytesRead;
var str = chunkBuffer.slice(0, bytesRead).toString();
var arr = str.split('\n');
if(bytesRead = chunkSize) {
// the last item of the arr may be not a full line, leave it to the next chunk
offset -= arr.pop().length;
}
lines.push(arr);
}
console.log(lines);
我有同样的问题,我已经解决了它与模块逐行
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.
});
另一个答案是使用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个字符的字符串”错误。