emreakyol
emreakyol

Reputation: 87

how to create a .csv file in node js

I'm new to node js. I'm trying to create a .csv file but I think something is wrong in my code;

const Json2csvParser = require('json2csv').Parser;

let fields = ["key1", "key2", "key3", "key4", "key5", "key6", "key7"]

let retval = {
    key1: ["a", "b", "c"],
    key2: ["a", "b", "c"],
    key3: ["a", "b", "c"],
    key4: ["a", "b", "c"],
    key5: ["a", "b", "c"],
    key6: ["a", "b", "c"],
    key7: ["a", "b", "c"]
};

const json2csvParser = new Json2csvParser({ fields });
const result = json2csvParser.parse(retval);

console.log(result);
fs.writeFile("localPath/test.csv", [result], "utf8", function (err) {
    if (err) {
        console.log('Some error occured - file either not saved or corrupted file saved.');
    } else{
        console.log('It\'s saved!');
    }
});

I wanna get this result:

key1 key2 key3 key4 key5 key6 key7
 a    a     a    a   a   a   a
 b    b     b    b   b   b   b
 c    c     c    c   c   c   c

but I got this;

"key1","key2","key3","key4","key5","key6","key7"
"[""a"",""b"",""c""]","[""a"",""b"",""c""]","[""a"",""b"",""c""]","[""a"",""b"",""c""]","[""a"",""b"",""c""]","[""a"",""b"",""c""]","[""a"",""b"",""c""]"

Where did I go wrong?

Upvotes: 1

Views: 2999

Answers (1)

Gabriel Bleu
Gabriel Bleu

Reputation: 10224

retval should be a list of rows :

[
  // row 1
  {
    key1: "a",
    key2: "a",
    key3: "a",
    key4: "a",
    key5: "a",
    key6: "a",
    key7: "a"
  },
  // row 2
  {
    key1: "b",
    key2: "b",
    key3: "b",
    key4: "b",
    key5: "b",
    key6: "b",
    key7: "b"
  }
  // more rows
];

see https://www.npmjs.com/package/json2csv#example-1

Upvotes: 3

Related Questions