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

我想,明显的解决scheme是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 。 只要创buildread stream ,pipe它到你的“检查function”,然后pipe它write stream

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

编辑:这个职位可以为你有用: 在Node.jsparsing巨大的日志文件 – 逐行阅读