'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 1:[1]

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);
})()

Solution 2:[2]

You can use "convert-excel-to-json" npm package. An example is as follows:

'use strict';
const excelToJson = require('convert-excel-to-json');
 
const result = excelToJson({
    sourceFile: 'SOME-EXCEL-FILE.xlsx'
});
 
// result will be an Object containing keys with the same name as the sheets found on the excel file. Each of the keys will have an array of objects where each of them represents a row of the container sheet. e.g. for a excel file that has two sheets ('sheet1', 'sheet2')
{
    sheet1: [{
        A: 'data of cell A1',
        B: 'data of cell B1',
        C: 'data of cell C1'
    }],
    sheet2: [{
        A: 'data of cell A1',
        B: 'data of cell B1',
        C: 'data of cell C1'
    }]
}

You can then use the result object anywhere.

Solution 3:[3]

You can try to use async and await, just write some code you want to execute in IIFE, the example:

  const csvFilePath = './aCSV.csv';
  const csv = require('csvtojson');
    
  // a IIFE
  (async () => {
    const jsonObj = await csv().fromFile(csvFilePath);
    console.log(jsonObj);
    // [ { a: '1', b: '2', c: '3' }, { a: '4', b: '5', c: '6' } ]
  })();

Solution 4:[4]

I am using convert-csv-to-json npm package. https://www.npmjs.com/package/convert-csv-to-json

let csv2Json = require('convert-csv-to-json');

let fileInputName = 'stores.csv';
let fileOutputName = 'stores.json';

csv2Json.fieldDelimiter(',').generateJsonFileFromCsv(fileInputName, fileOutputName);


let json = csv2Json.getJsonFromCsv("stores.csv");
for(let i=0; i<json.length;i++){
    console.log(json[i]);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Harsh Bharvada
Solution 3 Clark
Solution 4 FMA