gpt4 book ai didi

javascript - 如何使用node.js将大数组写入.txt文件?

转载 作者:太空宇宙 更新时间:2023-11-03 22:35:03 24 4
gpt4 key购买 nike

我认为,显而易见的解决方案是 fs.writeFile。

但是this的答案问题表明我应该使用 Stream 技术。

我目前正在尝试此代码,以便通过将文本文件转换为数组来从文本文件中删除一行:

var index = randomIntFromInterval(1, unfinished_searches.length-1); // remove index
unfinished_searches.splice(index, 1);

fs.truncate('unfinished_searches.txt', 0, function()
{
var file = fs.createWriteStream('unfinished_searches.txt');
file.on('error', function(err) { /* error handling */ });
unfinished_searches.forEach(function(v) { file.write(v.join(', ') + '\n'); });
file.end();
})

返回以下错误:

TypeError: undefined is not a function

在这一行的join处:

unfinished_searches.forEach(function(v) { file.write(v.join(', ') + '\n'); });

最佳答案

如果您想从大文本文件中删除行,请考虑使用管道。只需创建读取流,将其通过管道传输到“检查函数”,然后通过管道将其传输到写入流

这样您就不必将整个文件加载到内存中。内存中一次只有少量数据。当然你不能将它写入同一个文件。但完成操作后,您可以重命名该文件并删除旧文件。

编辑:这篇文章对您有用:Parsing huge logfiles in Node.js - read in line-by-line

关于javascript - 如何使用node.js将大数组写入.txt文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30760671/

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