首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我的JavaScript文件不能从另一个文件访问定义的常量?

为什么我的JavaScript文件不能从另一个文件访问定义的常量?
EN

Stack Overflow用户
提问于 2020-05-15 00:25:07
回答 2查看 47关注 0票数 0

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

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

keys.js:

代码语言:javascript
复制
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的结尾:

代码语言:javascript
复制
const importantMessage = 'RANDOM TEXT INTO BLOCKCHAIN'
buildOpReturnTransaction(myKeyPair, importantMessage)
.then(pushTransaction)
.then(response => console.log(response.data))

该问题与op_return.js中的常量myKeyPair有关,因为在node.js命令提示符中键入node op_return后会出现错误:

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

发布于 2020-05-15 01:00:52

在一个JavaScript文件中声明的变量不能在另一个文件中自动访问,但Node.js中有一项功能允许您通过modules导入和导出变量。

假设你在'file1.js‘中定义了变量myKeyPair,但是你想在'file2.js’中使用myKeyPair

解决方案是在file1.js中导出myKeyPair

代码语言:javascript
复制
// file1.js

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

module.exports.myKeyPair = myKeyPair;

然后,要在file2.js中使用myKeyPair,需要使用require()语句从file1.js导入它。

代码语言:javascript
复制
// file2.js

const myKeyPair = require('./file1.js');
票数 1
EN

Stack Overflow用户

发布于 2020-05-15 00:33:02

您已经在keys.js中定义了myKeyPair,而不是在op_return.js中。如果需要在一个文件中定义该变量并在另一个文件中使用它,则需要将该变量定义为全局变量。有关节点中的全局变量,请查看以下链接

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61802416

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档