6
votes

I'm new to node.js help me to solve this question.. In node.js it is showing like json2csv is not a function .. But i installed all packages of json2csv ... in node cmd "npm install json2csv" i did ..

        var json2csv = require('json2csv');
        var fs = require('fs');
        var json = [
          {
            "car": "Audi",
            "price": 40000,
            "color": "blue"
          }, {
            "car": "BMW",
            "price": 35000,
            "color": "black"
          }, {
            "car": "Porsche",
            "price": 60000,
            "color": "green"
          }
        ];
        json2csv({data: json, fields: ['car', 'price', 'color']}, function(err, csv) {
          if (err) console.log(err);
          fs.writeFile('file.csv', csv, function(err) {
            if (err) throw err;
            console.log('file saved');
          });
        });
    
    
` json2csv({data: json, fields: ['car', 'price', 'color']}, function(err, csv) { if (err) console.log(err); fs.writeFile('file.csv', csv, function(err) { if (err) throw err; console.log('file saved'); }); });
4

4 Answers

16
votes

You can use this:

const json2csv = require('json2csv').parse;

const csv = json2csv(json, fields);
console.log(csv);
1
votes

Have you referred the documentation https://github.com/zemirco/json2csv#json2csv-parser-synchronous-api about how to use the api ?

1
votes
const json2csv = require('json2csv');

const csv = await json2csv.parse(json, fields);
console.log(csv);
0
votes

jsonocsv is an event emitter so you have to use on some specific events for example

json2csv
  .on('header', header => console.log(header))
  .on('line', line => console.log(line))
  .on('error', err => console.log(err));

These threee are some of the emitter which trigger your function to run I think you will find what you want in the doucmentation examples and options section of the json2csv documentation