【问题标题】:node.js - how to write an array to filenode.js - 如何将数组写入文件
【发布时间】:2013-07-12 11:39:52
【问题描述】:

我有一个示例数组如下

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
......
......

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

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

    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();
    

    【讨论】:

    • 为什么不把file.end();放在循环之后而不是测试索引?
    • 谢谢!我的数组在 1000+ 左右,所以这个方法很有效
    • 奇怪,这给了我错误:TypeError: v.join is not a function,为了排除故障,我在循环中记录了typeof(v),它是一个字符串,coderade's solution 似乎没有产生错误。
    • @user1063287 仔细检查您是否传递了一个多维数组(如在 OP 中)
    【解决方案2】:

    请记住,您可以访问良好的旧 ECMAScript API,在本例中为 JSON.stringify()

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

    require('fs').writeFile(
    
        './my.json',
    
        JSON.stringify(myArray),
    
        function (err) {
            if (err) {
                console.error('Crap happens');
            }
        }
    );
    

    【讨论】:

    • 与 ArrayBuffers 无关
    • 如果myArray 很大,JSON.stringify(myArray) 就会成为问题。
    • 为了更好的可读性,可以使用JSON.stringify(myArray, null, 1)
    【解决方案3】:

    做你想做的事,以 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();
    

    【讨论】:

      【解决方案4】:

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

      require("fs").writeFile(
           somepath,
           arr.map(function(v){ return v.join(', ') }).join('\n'),
           function (err) { console.log(err ? 'Error :'+err : 'ok') }
      );
      

      【讨论】:

      • 如果你这样做了,不要忘记带有 err 的回调:nodejs.org/api/…
      • 不确定有什么问题,但我的系统在编写的这段代码上吐了。 TypeError: v.join is not a function
      • 'ok' 之后缺少)
      • @3zzy 谢谢,已修复。请注意,您可以在 SO 上编辑答案
      • 语法错误需要添加 arr.map(function(v){ return v.join(', ') >>}
      【解决方案5】:
      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'));
      }
      

      【讨论】:

        【解决方案6】:

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

        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

        不会有帮助。 请参考this

        【讨论】:

        • 这取决于运行脚本的操作系统。对于 Linux,\n 是有效的换行符。对于 Windows,您需要 \r\n
        猜你喜欢
        • 1970-01-01
        • 2015-08-25
        • 2018-07-04
        • 2017-08-31
        • 2016-05-13
        • 2012-11-22
        • 2020-05-10
        • 1970-01-01
        相关资源
        最近更新 更多