4

I've seen code examples of using csvtojson, but each one simply outputs the result using console.log(). The following code creates a variable named 'json', but I don't see how I can use this outside of the function creating it. How can I export the variable 'json' for use outside of the function that is creating it?:

const csvFilePath='<path to csv file>'
const csv=require('csvtojson')

csv().fromFile(csvFilePath,function(err,result){

    if(err){
        console.log("An Error Has Occured");
        console.log(err);  
    } 

    var json = result; // I want to use this var outside of this function.
    console.log(json);
});

I was really hoping that it would be as simple as writing something like:

const dataArray = csv().fromFile(csvFilePath);

But, dataArray doesn't contain my data, but instead appears to be an object with parameters about the data.

Any clues will be greatly appreciated!

Tony Guinta
  • 633
  • 1
  • 8
  • 14
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Lux Nov 10 '18 at 21:05
  • 1
    Very close: `const jsonArray = await csv().fromFile(csvFilePath);` https://www.npmjs.com/package/csvtojson#from-csv-file-to-json-array – Jonathan Nov 10 '18 at 22:31

3 Answers3

1

The problem is that fromFile is asynchronous, and once you have called async code, you live in the callback.

The module doesn't seem to provide a sync alternative. Your options are:

  • Continue your program logic inside the callback:

csv().fromFile(csvFilePath,function(err,result){

    if(err){
        console.log("An Error Has Occured");
        console.log(err);  
    } 

    var json = result; 
    console.log(json);

    // Continue your logic here
    // .....
    // .....
});
  • Use async/await

You seem to be using an older version of csvtojson, so you might need to upgrade it to use this:

(async () => {

  var jsons =  await csv().fromFile(csvFilePath);
  console.log(jsons);

})()
.catch((err) => {
  console.log(err);
});

Basically this wraps your code inside an async function. Inside it, you can use the return value of fromFile if you use the await keyword.

  • Use a different module that supports sync loading or even do the parsing yourself.
mihai
  • 37,072
  • 9
  • 60
  • 86
0

csvJSON function with functional map

var csvJSON = function(csv){
   var lines = csv.split("\n");
   var result = [];
   var headers = lines[0].split(",");
  lines.map(function(line, indexLine){
    if (indexLine < 1) return // Jump header line
     var obj = {};
     var currentline = line.split(",");
   headers.map(function(header, indexHeader){
      obj[header] = currentline[indexHeader];
    })
   result.push(obj);
  })
 result.pop(); // remove the las`enter code here`t item because undefined values
 return result; // JavaScript object
}
Mehar
  • 1
  • 1
0

I've learned a bit about async functions and promises since I posted this question. Since csvjson returns promises, I return the result of csv() to the next function in my chain:

    const csv = require('csvtojson');
    const filePath = '<path to csv file>';

    // previous async function in promise chain
    .then(() => {
      return csv().fromFile(filePath)
    })
    .then(data => { // 'data' contains the json as converted by csv()
      // next step in promise chain
    })
Tony Guinta
  • 633
  • 1
  • 8
  • 14