简体   繁体   English

将数组写入文件 fs

[英]Write an array into an file fs

I want to create a .txt file which contains my array, using fs.我想使用 fs 创建一个包含我的数组的 .txt 文件。

My array looks like this:我的数组如下所示:

const array = [1111, 2222, 33333]

The code below allows me to write in the file and seperate each entry with a comma but I cant get them on a new line.下面的代码允许我在文件中写入并用逗号分隔每个条目,但我无法将它们放在新行上。 Neither using \n nor \r\n既不使用\n也不使用\r\n

await fs.writeFile('Participants.txt', `${array}, \r\n`);

Thanks for your help in advance.提前感谢您的帮助。

Is something like this what you are looking for?你正在寻找这样的东西吗?

const array = [1111, 2222, 33333]
var arrayLength = array.length;
for (var i = 0; i < arrayLength; i++) {
    fs.appendFile('Participants.txt', `${array[i]}\n`);
}

What you are looking for is array.join() :您正在寻找的是array.join()

const text_string = eligible.join('\n');

await fs.writeFile('Participants.txt', text_string);

In the example above I separated out the string you want to write to the file into a variable for clarity so that it is obvious what's going on.在上面的示例中,为了清楚起见,我将要写入文件的字符串分离到一个变量中,以便清楚地知道发生了什么。 Of course you could skip the extra variable and just do eligible.join('\n') directly in the fs.writeFile() but I wanted to make it clear that this feature has nothing to do with fs nor any string syntax nor any function argument syntax.当然,您可以跳过额外的变量,直接在fs.writeFile()中执行qualified.join( eligible.join('\n') ) 但我想明确指出,此功能与fs无关,也与任何字符串语法无关函数参数语法。 It is simply a feature of Arrays.它只是数组的一个特性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM