繁体   English   中英

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

[英]How to write big array to .txt file using node.js?

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

但是这个问题的答案表明我应该使用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'); });

如果要从大文本文件中删除行,请考虑使用pipes 只需创建read stream ,将其通过管道传递到“检查功能”,然后通过管道将其write stream

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

编辑:这篇文章可能对您有用: 在Node.js中解析巨大的日志文件-逐行阅读

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM