node.js - 如何将数组写入文件

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)

  • 为什么不在循环之后放置`file.end();`而不是测试索引? (2认同)
  • 奇怪的是,这给了我错误:`TypeError:v.join不是一个函数`,要进行故障排除,我在循环内记录了`typeof(v)`,它是一个字符串,[编码器的解决方案](https:// stackoverflow .com / a / 51362713)似乎没有产生错误。 (2认同)
  • @user1063287仔细检查您是否传递了多维数组(如OP中所示) (2认同)

小智 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)

  • 如果`myArray`很大,`JSON.stringify(myArray)`将成为一个问题. (2认同)
  • 为了更好的可读性,您可以使用`JSON.stringify(myArray, null, 1)` (2认同)

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)

  • 不知道有什么不妥,但是我的系统在写这个代码时会呕吐.`TypeError:v.join不是函数` (2认同)

cod*_*ade 7

要执行您想要的操作,请以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)