-1

I am working on Electron.JS and am pushing JSON file contents into a variable (global). But the variable doesn't show the contents outside file-read code block.

var fs = require('fs');
var nodeConsole = require('console');
var myConsole = new nodeConsole.Console(process.stdout, process.stderr);
var dir = __dirname+'/gstn';

var itemsDoubleList = [];

fs.readFile(dir+'/items.json', 'utf8', function(err, data){
    if(err)
        myconsole.log(err)
    else{

        for(var i=0; i<(JSON.parse(data)).length; i++){
            var temp = (JSON.parse(data))[i]; 
            itemsDoubleList.push([temp.hsnCode, temp.itemName, temp.itemUnit, temp.itemRate, temp.itemGST]);
        }
    }
    myConsole.log(itemsDoubleList); //shows file contents
});


myConsole.log(itemsDoubleList); // doesn't show file contents

1 Answers1

0

The readFile function asynchronously reads the contents of a file, so when you log itemsDoubleList just after calling readFile, it isn't set yet.

You may use fs.readFileSync which is the sync version of readFile

Saeed
  • 7,262
  • 14
  • 43
  • 63