Viper
Viper

Reputation: 1397

Write array to a CSV in nodejs

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"]

Upvotes: 7

Views: 13963

Answers (1)

GrafiCode
GrafiCode

Reputation: 3374

[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');

Upvotes: 5

Related Questions