为什么我的JavaScript文件无法读取定义的常量?

问题描述 投票:0回答:2

我将使用OP_RETURN(testnet)将数据嵌入到区块链中。

我在一个目录中有两个文件。第一个keys.js包含为比特币测试网交易生成地址和私钥的代码。

keys.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))

问题出在myKeyPair中的常数op_return.js上,因为在node.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 blockchain bitcoin bitcoin-testnet
2个回答
0
投票

您已在myKeyPair中定义了keys.js,而不是在op_return.js中定义。如果需要在一个文件中定义它,而在另一个文件中使用它,则需要将变量定义为全局变量。在节点中检查以下链接以获取全局变量

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


0
投票

在一个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');
© www.soinside.com 2019 - 2024. All rights reserved.