70

我有一个示例数组如下

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

我想将此数组写入一个文件,例如我得到一个文件如下

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

6 回答 6

118

如果它是一个巨大的数组,并且在写入之前将其序列化为字符串需要太多内存,则可以使用流:

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();
于 2013-07-12T11:46:49.430 回答
46

请记住,您可以访问良好的旧 ECMAScript API,在这种情况下,JSON.stringify().

对于像您的示例中的简单数组:

require('fs').writeFile(

    './my.json',

    JSON.stringify(myArray),

    function (err) {
        if (err) {
            console.error('Crap happens');
        }
    }
);
于 2015-04-04T12:00:47.840 回答
24

做你想做的事,以 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();
于 2018-07-16T13:14:16.147 回答
13

一个简单的解决方案是使用writeFile

require("fs").writeFile(
     somepath,
     arr.map(function(v){ return v.join(', ') }).join('\n'),
     function (err) { console.log(err ? 'Error :'+err : 'ok') }
);
于 2013-07-12T11:42:17.930 回答
4
async function x(){
var arr = [ [ 1373628934214, 3 ],
[ 1373628934218, 3 ],
[ 1373628934220, 1 ],
[ 1373628934230, 1 ],
[ 1373628934234, 0 ],
[ 1373628934237, -1 ],
[ 1373628934242, 0 ],
[ 1373628934246, -1 ],
[ 1373628934251, 0 ],
[ 1373628934266, 11 ] ];
await fs.writeFileSync('./PATH/TO/FILE.txt', arr.join('\n'));
}
于 2021-04-04T11:21:07.660 回答
3

我们可以简单地将数组数据写入文件系统,但这会引发一个错误,其中 ',' 将被附加到文件末尾。要处理此问题,可以使用以下代码:

var fs = require('fs');

var file = fs.createWriteStream('hello.txt');
file.on('error', function(err) { Console.log(err) });
data.forEach(value => file.write(`${value}\r\n`));
file.end();

\r\n

用于新线路。

\n

不会有帮助的。请参考这里

于 2019-06-23T13:44:01.840 回答