Converting json to csv using json2csv package asynchronously using parseAsync throws error

2.2k Views Asked by At

I am using a json2csv for converting a json response to csv. I need to use this as asynchronous. So that it should not block other api calls. The below code I tried but it throws an error. "TypeError: parseAsync is not a function"

const parseAsync = require("json2csv")       
    mycollection.aggregate(aggquery, function (err, jsondata) {    
       parseAsync(jsondata, opts).then(csv => console.log(csv))
         .catch(err => console.error(err));    
    });

After converting csv I need to write that in a file.

2

There are 2 best solutions below

2
On

You should be able to use parseAsync, then write the resulting CSV data to a file using fs.writeFile.

const { parseAsync } = require("json2csv")
const fs = require("fs");
const filePath = "./csvdata.csv"; // Enter file path here...

mycollection.aggregate(aggquery, async function(err, jsondata) {
    if (err) {
        console.error("mycollection.aggregate: An error occurred:", err);
        return;
    }
    try { 
        const csv = await parseAsync(jsondata, {});
        fs.writeFile(filePath, csv, { encoding: "utf-8" }, (fileErr) => { 
            if (fileErr) {
                console.error("mycollection.aggregate: Error writing CSV to file:", fileErr);
            }
        })
    } catch (err) {
        console.error("mycollection.aggregate: parseAsync: An error occurred:", err);
    }
});
0
On

According to the json2csv docs, parseAsync() is not the default export but a property of the export instead. In other words, instead of this:

const parseAsync = require("json2csv")

...you want this:

const { parseAsync } = require("json2csv")

That will get you past the error you're seeing about parseAsync() not being a function.