我有一些很难在内存中读取的大文件。我需要阅读每一行,然后在找到后替换双引号并编辑相同的文件。现在,我正在逐行读取文件,将其存储在数组中并覆盖同一文件。但是,这给大文件带来了内存问题。有指针吗?这是我目前的实现:
var allData = fs.readFileSync(fileName, { encoding: 'utf8' }).toString().split("\n");
var finalString = "";
for (i in allData) {
allData[i] = allData[i].replace(/"/g, '""');
finalString = finalString.concat(allData[i]);
finalString = finalString.concat("\n");
}
fs.writeFileSync(fileName, finalString);
是否可以通过一次读取一行并在文件中进行更改来进行编辑?
我已经用scramjet看到了类似的问题,但这给出了一个错误并且与所有的nodejs版本都不兼容:node.js modify file data stream?
经过大量回答后,这对我有用,它处理了所需的同步和异步行为,大文件并保持名称不变。
function format_file(fileName) {
return new Promise((resolve, reject) => {
if (fs.existsSync(fileName)) {
var fields = fileName.split('/');
var tempFile = "";
var arrayLength = fields.length;
for (var i = 0; i < arrayLength - 1; i++) {
tempFile = tempFile + fields[i] + "/";
}
tempFile = tempFile + "tempFile" + fields[arrayLength - 1];
console.log("tempfile name is : " + tempFile + " actualFileName is :" + fileName);
var processStream = new ProcessStream();
fs.createReadStream(fileName, { bufferSize: 128 * 4096 })
.pipe(processStream)
.pipe(fs.createWriteStream(tempFile)).on('finish', function() { // finished
fs.renameSync(tempFile, fileName);
console.log('done encrypting');
resolve('done');
});
} else {
reject('path not found')
}
});
}