gpt4 book ai didi

node.js - Nodejs for 循环 - 流内存不足

转载 作者:太空宇宙 更新时间:2023-11-03 23:14:29 25 4
gpt4 key购买 nike

我正在生成一个想要保存的 CSV 文件。虽然有点大,但是代码很简单。我使用流来防止内存不足错误,但无论如何它都会发生。有什么建议吗?

const fs = require('fs');
var noOfRows = 2000000000;
var stream = fs.createWriteStream('myFile.csv', {flags: 'a'});
for (var i=0;i<=noOfRows;i++){
var col = '';
col += i;
stream.write(col)
}

最佳答案

添加一个drain事件监听器。

const fs = require("fs");
var noOfRows = 2000000000;
var stream = fs.createWriteStream("myFile.csv", { flags: "a" });
var i = 0;

function write() {
var ok = true;
do {
var data = i + "";
if (i === noOfRows) {
// last time!
stream.write(data);
} else {
// see if we should continue, or wait
// don't pass the callback, because we're not done yet.
ok = stream.write(data);
}
i++;
} while (i<=noOfRows && ok);
if (i < noOfRows) {
// had to stop early!
// write some more once it drains
stream.once("drain", write);
}
}

write();

而且 noOfRows 太大,可能会导致您的 .csv 文件大小超出磁盘大小

关于node.js - Nodejs for 循环 - 流内存不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57268604/

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