0

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.

N0rmal
  • 47
  • 1
  • 7
  • see: [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) – pilchard May 17 '22 at 18:19
  • What is `eligible`? Should that be `array`? – Barmar May 17 '22 at 18:27
  • @Barmar sry you are right my bad. Corrected it – N0rmal May 17 '22 at 19:13
  • @pilchard I have read somewhere that this can cause problems with bigger arrays – N0rmal May 17 '22 at 19:14
  • You indicate that you have an array with three elements in it. – pilchard May 17 '22 at 20:12
  • Duplicate: [How to print each element of an array in new line in txt file using javascript?](https://stackoverflow.com/questions/52190559/how-to-print-each-element-of-an-array-in-new-line-in-txt-file-using-javascript) – pilchard May 17 '22 at 20:16
  • also: [node.js - how to write an array to file](https://stackoverflow.com/questions/17614123/node-js-how-to-write-an-array-to-file) – pilchard May 17 '22 at 20:38

2 Answers2

1

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`);
}
0

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.

slebetman
  • 109,858
  • 19
  • 140
  • 171
  • You may also be interested in the opposite of `.join()` which is `.split()`. While `.join()` merges an array into a string `.split()` breaks up a string into an array. – slebetman May 17 '22 at 18:31