簡體   English   中英

為什么我的 JavaScript 文件無法從另一個文件訪問定義的常量?

[英]Why my JavaScript file can't access defined constant from another file?

我將使用 OP_RETURN (testnet) 將數據嵌入到區塊鏈中。

我在一個目錄中有兩個文件。 第一個keys.js包含為比特幣測試網交易生成地址和私鑰的代碼。

鍵.js:

const bitcoin = require('bitcoinjs-lib');
const { testnet } = bitcoin.networks
const myKeyPair = bitcoin.ECPair.makeRandom({ network: testnet });
//extract the publickey
const publicKey = myKeyPair.publicKey;
//get the private key
const myWIF = myKeyPair.toWIF();
//get an address from the myKeyPair we generated above.
const { address } = bitcoin.payments.p2pkh({
  pubkey: publicKey,
  network: testnet
});

console.log("myAdress: " + address + " \nmyWIF: " + myWIF);

第二個op_return.js包含允許我將隨機文本嵌入區塊鏈的方法。

這是 op_return.js 的結尾:

const importantMessage = 'RANDOM TEXT INTO BLOCKCHAIN'
buildOpReturnTransaction(myKeyPair, importantMessage)
.then(pushTransaction)
.then(response => console.log(response.data))

問題在於 op_return.js 中的常量myKeyPair ,因為在op_return.js命令提示符錯誤中鍵入node op_return后:

buildOpReturnTransaction(myKeyPair, importantMessage)
                         ^

ReferenceError: myKeyPair is not defined
    at Object.<anonymous> (C:\Users\Paul\Desktop\mydir\op_return:71:26)
    at Module._compile (internal/modules/cjs/loader.js:1133:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
    at Module.load (internal/modules/cjs/loader.js:977:32)
    at Function.Module._load (internal/modules/cjs/loader.js:877:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47

在 JavaScript 文件中聲明的變量不能在其他文件中自動訪問,但 Node.js 中有一項可用功能,可讓您通過模塊導入和導出變量。

假設您在“file1.js”中定義了變量myKeyPair ,但您想在“file2.js”中使用myKeyPair

解決辦法是在file1.js中導出myKeyPair

// file1.js

const myKeyPair = ['hello', 'world'];

module.exports.myKeyPair = myKeyPair;

然后,要在 file2.js 中使用myKeyPair ,請使用require()語句從 file1.js 導入它。

// file2.js

const myKeyPair = require('./file1.js');

您在myKeyPair中定義了keys.js而不是在op_return.js中。 如果您需要在一個文件中定義它並在另一個文件中使用它,則需要將變量定義為全局變量。 查看下面的鏈接以獲取節點中的全局變量

https://stackabuse.com/using-global-variables-in-node-js/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM