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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17614123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:01:34  来源:igfitidea点击:

node.js - how to write an array to file

javascriptnode.js

提问by dopplesoldner

I have a sample array as follows

我有一个示例数组如下

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

回答by mak

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

回答by Jairo

Remember you can access good old ECMAScript APIs, in this case, JSON.stringify().

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

For simple arrays like the one in your example:

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

require('fs').writeFile(

    './my.json',

    JSON.stringify(myArray),

    function (err) {
        if (err) {
            console.error('Crap happens');
        }
    }
);

回答by Denys Séguret

A simple solution is to use writeFile:

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

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

回答by valdeci

To do what you want, using the fs.createWriteStream(path[, options])function in a ES6 way:

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

回答by KamalDeep

We can simply write the array data to the filesystem but this will raise one error in which ',' will be appended to the end of the file. To handle this below code can be used:

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

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

\r\n

is used for the new Line.

用于新线。

\n

\n

won't help. Please refer this

不会有帮助。请参考这个