node.js - 如何将数组写入文件 [英] node.js - how to write an array to file

查看:432
本文介绍了node.js - 如何将数组写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个样本数组如下

var arr = [ [ 1373628934214, 3 ],
  [ 1373628934218, 3 ],
  [ 1373628934220, 1 ],
  [ 1373628934230, 1 ],
  [ 1373628934234, 0 ],
  [ 1373628934237, -1 ],
  [ 1373628934242, 0 ],
  [ 1373628934246, -1 ],
  [ 1373628934251, 0 ],
  [ 1373628934266, 11 ] ]

我想把这个数组写成一个文件,比如我得到一个文件如下

I would like to write this array to a file such as I get a file as follows

1373628934214, 3 
1373628934218, 3
1373628934220, 1
......
......


推荐答案

如果它是一个huuge数组并且需要太多内存才能将其序列化为a在写之前,你可以使用流:

If it's a huuge array and it would take too much memory to serialize it to a string before writing, you can use streams:

var fs = require('fs');

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

这篇关于node.js - 如何将数组写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆