简体   繁体   中英

Write an array into an file fs

I want to create a .txt file which contains my array, using fs.

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

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

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. It is simply a feature of Arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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