[英]Undefined variable, nodejs, json to program variable
我決定以骯臟的方式將數據保存到 .json 文件中。 出於某種原因,當我運行運行我編寫的其他模塊的 index.js 文件時,它說我在單獨的模塊中初始化的特定變量是未定義的(我希望從 json 引用一個)。 我的程序結構是標准索引文件,它從我編寫的模塊中加載函數並通過端點執行它們。
.json 文件
{"blocks":[{"GENESIS_DATA":{"timestamp":1,"lastHash":"v01d","hash":"?M=(((Position-1)=>ter)=>sen)=>non?","difficulty":20,"nonce":0,"data":[]}}]}
我想獲取這個名為 GENESIS_DATA 的數組的第一個索引並將其用作我的程序中的數組...
來自區塊鏈索引的相關代碼(不是我為程序運行而執行的文件)
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*/
}
錯誤日志
/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]#
首先,常量創世是回調本地的,所以它在回調完成運行后被銷毀。 此外,即使常量是在回調之外聲明的,請記住 fs.readFile 是異步的,因此當 readFile 讀取包含數據的文件時,常量 genesis 已經設置為未定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.