0

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.

user1187
  • 2,116
  • 8
  • 41
  • 74

2 Answers2

0

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.

Trott
  • 66,479
  • 23
  • 173
  • 212
0

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);
    }
});
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
  • 1
    Since its a async -await . It will bock my other api calls. – user1187 Oct 01 '20 at 09:48
  • It won't block the calls, the aggregate function will not wait for the callback to complete. You could do some testing to ensure this is the case, but I can promise you it won't block the calls. – Terry Lennox Oct 01 '20 at 10:05