AmishJohn81 AmishJohn81 - 5 months ago 29
JSON Question

How to access variables that are inside a callback function of a JavaScript event?

I am trying to use

csvtojson
to convert a CSV file to JSON. I an using the
csvtojson
library and
fs
to read the file in. I can get it convert but, I cannot figure out how to access the variables afterwards. I am new to javascript, and the techniques that I thought would work coming from other languages have not worked... I am calling the function from another js file, and want to be able to access variables from the
converter.on('end_parsed'...)
function. Code Below

'use strict'

const fs = require('fs')
const Converter = require('csvtojson').Converter

exports.myfuncc = function () {
var converter = new Converter({})
var csvEncoding = { encoding: 'utf16le' }
var csvString = fs.readFileSync('C:\\Users\\jgipe\\Desktop\\csvs\\201508.txt', csvEncoding).toString()
converter.fromString(csvString, function (err, result) {
if (err) { console.log(err) }
})

converter.on('end_parsed', function (jsonArray) {
// Just examples of the data contained in one object
console.log(jsonArray[9]['Date'])
console.log(jsonArray[9]['Package Name'])
console.log(jsonArray[9]['Current Device Installs'])
console.log(jsonArray[9]['Daily Device Installs'])
console.log(jsonArray[9]['Daily Device Uninstalls'])
console.log(jsonArray[9]['Daily Device Upgrades'])
console.log(jsonArray[9]['Current User Installs'])
console.log(jsonArray[9]['Total User Installs'])
console.log(jsonArray[9]['Daily User Installs'])
console.log(jsonArray[9]['Daily User Uninstalls'])
})
}

Answer

Put the callback function as parameter for exports.myfuncc, like this:

'use strict'

const fs = require('fs')
const Converter = require('csvtojson').Converter

exports.myfuncc = function (callback) {
  var converter = new Converter({})
  var csvEncoding = { encoding: 'utf16le' }
  var csvString = fs.readFileSync('C:\\Users\\jgipe\\Desktop\\csvs\\201508.txt', csvEncoding).toString()
  converter.fromString(csvString, function (err, result) {
    if (err) { console.log(err) }
  })

  converter.on('end_parsed', callback)
}

Then in another file call it like this:

exports.myfuncc(function(jsonArray){
    // You can access jsonArray...
});