javascriptjsoncsvtojson

How to get JSON data out of csvtojson scope?


I'm new to Javascript, maybe you can help me understand this. The csvtojson examples here all show logging to the console which works fine:

https://www.npmjs.com/package/csvtojson#from-csv-file-to-json-array

const csvFilePath='<path to csv file>'
const csv=require('csvtojson')
csv()
.fromFile(csvFilePath)
.then((jsonObj)=>{
    console.log(jsonObj);
})

My question is - how do I use jsonObj outside of this scope? I just want a simple global variable that I can access the JSON with later in the script.


Solution

  • You can use an IIFE (Immediately Invoked Function Expression) to wrap all your asynchronous code and store the value in a global variable and can acess that inside the asynchronous IIFE. To store the value and acess it from any where you have to await for the result and then acess the value due to asynchronous and single thread nature of js.

    const csv = require('csvtojson');
    
    let arr = [];
    
    (async function () {
        const json = await csv().fromFile('./demo.csv');
        await arr.push(json);
        console.log(arr);
    })()