常量?"/>
为什么我的JavaScript文件无法读取定义的常量?
我将使用OP_RETURN(testnet)将数据嵌入到区块链中。
我在一个目录中有两个文件。第一个keys.js
包含为比特币测试网交易生成地址和私钥的代码。
keys.js:
const bitcoin = require('bitcoinjs-lib');
const { testnet } = bitcoinworks
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
回答如下:您已在myKeyPair
中定义了keys.js
,而不是在op_return.js
中定义。如果需要在一个文件中定义它,而在另一个文件中使用它,则需要将变量定义为全局变量。在节点中检查以下链接以获取全局变量
https://stackabuse/using-global-variables-in-node-js/
更多推荐
为什么我的JavaScript文件无法读取定义的常量?
发布评论