Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 333
Viper Avatar asked Aug 08 '26 18:08

Viper


1 Answers

[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');
like image 171
GrafiCode Avatar answered Aug 10 '26 07:08

GrafiCode