0

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.

beemo
  • 27
  • 7
  • You can try to use `async` `await` or a callback function. – Clark Dec 29 '20 at 05:33
  • Any simple examples so I can see how that works? I've seen several references to using "async" but no basic examples of how to do it. Just console.log which doesn't help me... – beemo Dec 29 '20 at 05:35
  • Hi, I added the example below. If you have any questions, just ask :) – Clark Dec 29 '20 at 05:59

4 Answers4

2

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);
})()
Apratim
  • 204
  • 2
  • 9
  • I don't think this is correct. My IDE says that the `await arr.push(json)` line has no effect, and wants to remove the await. Also `arr` is not available outside the function. :-( – beemo Dec 29 '20 at 14:18
  • Why `await arr.push(json)` is not correct? Can you please explain? To store the value and acess it from any where using `promise` you have to await for the result and then acess the value due to asynchronous and single thread nature of js. – Apratim Dec 29 '20 at 14:56
  • Or you can use any synchronous method. But It will block your main thread. – Apratim Dec 29 '20 at 15:06
1

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.

1

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' } ]
  })();
Clark
  • 305
  • 1
  • 8
0

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]);
}
FMA
  • 16
  • 3