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!

4

3 回答 3

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.
于 2018-11-11T09:43:55.567 回答
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
}
于 2018-11-10T22:57:36.703 回答
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
    })
于 2018-12-08T21:12:59.107 回答