Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Array to text with newline

I wanted to convert an array to a textfile with a newline separating each entry.

I found out about an npm package called array-to-txt-file. Here is the webpage: array-to-txt-file

This package claims that will concatenate every element of the array with a newline, so that every element of the array appears on its own line on the text file.

So i gave it a try and while it works great it doesn't concatenate the elements with a newline. Where one element ends, another one begins.

So i took a look at the source code of the package and this is the code that creates this effect.

try {
    array.forEach(v => {
      if(_.isPlainObject(v)) {
        ws.write(`${JSON.stringify(v)}\n`)
        return
      }
      ws.write(`${v}\n`)
    })

Especially the ws.write(${v}\n) part.

I then imported my output text file into a hex editor. In the hex editor there was dot between each element. Now, this dot was different to a regular dot.

While a regular dot has the hex value of 2E, the dot that appears between the elements has 0A. Please also note that i am using Windows 7, and when viewed with notepad, nothing appears between the elements - where one ends, another one begins straight up.

So is there a way to modify that line in the code i posted above, so it really creates a newline in that part?

like image 932
user1584421 Avatar asked Oct 31 '25 10:10

user1584421


1 Answers

Is there some reason a simple join doesn't work for you?

let arr = ["a", "b", "c", "d", "e", "f"];

console.log(arr); // [ 'a', 'b', 'c', 'd', 'e', 'f' ]

console.log(arr.join('\n'));
// a
// b
// c
// d
// e
// f

let text = arr.join('\n');

fs.writeFileSync('modified.txt', text, "utf8");

If you need to you can replace \n with \r\n in the join as @Saif suggests, but I don't seem to need to, perhaps vscode is doing this automatically for me though. I'm on a Windows machine.

like image 137
Mark Avatar answered Nov 02 '25 01:11

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!