Search code examples
javascriptnode.jsjsonundefinedvisual-web-developer

Undefined variable, nodejs, json to program variable


I decided to save data the dirty way to a .json file. For some reason, when I run my index.js file which runs other modules I have written, it says that a particular variable I initialized in a separate module is undefined (one I was hoping to reference from json). The structure of my program is the standard index file that loads functions from modules I have written and executes them via endpoints.

.json File

{"blocks":[{"GENESIS_DATA":{"timestamp":1,"lastHash":"v01d","hash":"?M=(((Position-1)=>ter)=>sen)=>non?","difficulty":20,"nonce":0,"data":[]}}]}

I want to take the first index of this array named GENESIS_DATA and use it as an array in my program...

relevant code from blockchain index (not the file I execute for the program to run)

const { REWARD_INPUT, MINING_REWARD, GENESIS_DATA } = require('../config');
const fs = require('fs');
const jsonRoute = '/home/main/public_html/Cypher-Network/CDSM/CDSM.json';

class Blockchain {
  constructor() {
fs.readFile(jsonRoute, 'utf-8', function(err, data) {
    if (err) throw err;

    this.jsonChain = JSON.parse(data);
    const genesis = jsonChain.blocks[0];
});
    this.chain = [genesis];
  }

/*Alot more code down here but let's assume that the bracket for class Blockchain is completed*/
}

error log

/home/main/public_html/Cypher-Network/blockchain/index.js:32
    this.chain = [genesis]; //we are taking the first element of the json file (genesis block)
                  ^

ReferenceError: genesis is not defined
    at new Blockchain (/home/main/public_html/Cypher-Network/blockchain/index.js:32:19)
    at Object.<anonymous> (/home/main/public_html/Cypher-Network/index.js:28:20)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47
main@goldengates.club [~/public_html/Cypher-Network]#


Solution

  • First, the constant genesis is local to the callback, so it is getting destroyed just after the callback has finished running. Also even if the constant was declared outside the callback, remember that fs.readFile is asynchronous, so while readFile is reading the file containing the data, the constant genesis will have already been set to undefined.