7

I'm trying to write an array to a CSV using the fs module in node. Every time do so, it creates new columns because of the commas in the array. How can I go about doing this without creating new columns - the array should be contained within the column. My code below.

const fs = require('fs');
const writeStream = fs.createWriteStream('data.csv');
writeStream.write(`brands \n`);
writeStream.write(`${brands}\n`);

The array is just a list of strings: var brands = ["h2O, "glycerin", "cetyl", "ethylhexanoate"]

1 Answer 1

5

[edit after OP's clarification]

You can use Array.join() to join single elements wrapping them in double-quotes and separating them with commas:

const fs = require('fs');

const brands = ["h2O", "glycerin", "cetyl", "ethylhexanoate"]

const writeStream = fs.createWriteStream('data.csv');


writeStream.write(`brands \n`);

writeStream.write('[ "' + brands.join('","') + '" ]\n');
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but I want to put all the items in an array format in the same row. So for example: the brands row would have "["h2O, "glycerin", "cetyl", "ethylhexanoate"]"
@Viper You need the square brackets and double-quotes too?
Yes, i do need this
@Viper Edited my answer according to your clarification. Does it help?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.