在Node.js中将数组写入CSV

时间:2019-07-01 15:47:33

标签: arrays node.js csv fs

我正在尝试使用节点中的fs模块将数组写入CSV。每次这样做,都会由于数组中的逗号而创建新的列。如何在不创建新列的情况下进行此操作-数组应包含在列中。我的代码如下。

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

该数组只是一个字符串列表:var brands = ["h2O, "glycerin", "cetyl", "ethylhexanoate"]

1 个答案:

答案 0 :(得分:1)

[澄清OP后的修改]

您可以使用Array.join()来连接单个元素,将其用双引号引起来并用逗号分隔:

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