dop*_*ner 43 javascript node.js
我有一个示例数组如下
var arr = [ [ 1373628934214, 3 ],
[ 1373628934218, 3 ],
[ 1373628934220, 1 ],
[ 1373628934230, 1 ],
[ 1373628934234, 0 ],
[ 1373628934237, -1 ],
[ 1373628934242, 0 ],
[ 1373628934246, -1 ],
[ 1373628934251, 0 ],
[ 1373628934266, 11 ] ]
Run Code Online (Sandbox Code Playgroud)
我想把这个数组写成一个文件,比如我得到一个文件,如下所示
1373628934214, 3
1373628934218, 3
1373628934220, 1
......
......
Run Code Online (Sandbox Code Playgroud)
mak*_*mak 73
如果它是一个huuge数组并且在写入之前将其序列化为字符串需要太多内存,则可以使用流:
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();
Run Code Online (Sandbox Code Playgroud)
小智 19
请记住,在这种情况下,您可以访问好的旧ECMAScript API JSON.stringify()
.
对于像示例中的简单数组:
require('fs').writeFile(
'./my.json',
JSON.stringify(myArray),
function (err) {
if (err) {
console.error('Crap happens');
}
}
);
Run Code Online (Sandbox Code Playgroud)
Den*_*ret 11
一个简单的解决方案是使用writeFile:
require("fs").writeFile(
somepath,
arr.map(function(v){ return v.join(', ') }).join('\n'),
function (err) { console.log(err ? 'Error :'+err : 'ok') }
);
Run Code Online (Sandbox Code Playgroud)
要执行您想要的操作,请以ES6方式使用fs.createWriteStream(path [,options])函数:
const fs = require('fs');
const writeStream = fs.createWriteStream('file.txt');
const pathName = writeStream.path;
let array = ['1','2','3','4','5','6','7'];
// write each value of the array on the file breaking line
array.forEach(value => writeStream.write(`${value}\n`));
// the finish event is emitted when all data has been flushed from the stream
writeStream.on('finish', () => {
console.log(`wrote all the array data to file ${pathName}`);
});
// handle the errors on the write process
writeStream.on('error', (err) => {
console.error(`There is an error writing the file ${pathName} => ${err}`)
});
// close the stream
writeStream.end();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
71478 次 |
最近记录: |