简体   繁体   中英

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

I'm going to embed data into the blockchain with OP_RETURN (testnet).

I have two files in one directory. The first one keys.js contains code that generates address and private key for bitcoin testnet transactions.

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);

The second one op_return.js contains method that allows me to embed random text into blockchain.

This is the end of op_return.js:

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

The problem is with constant myKeyPair in op_return.js because after typing node op_return in node.js command prompt error comes out:

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

A variable declared in one JavaScript file is not automatically accessible in a different file, but there is a feature available in Node.js that lets you import and export variables via modules .

Say you have defined the variable myKeyPair in 'file1.js', but you want to use myKeyPair in 'file2.js'.

The solution is to export myKeyPair in file1.js:

// file1.js

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

module.exports.myKeyPair = myKeyPair;

Then, to use myKeyPair in file2.js, you import it from file1.js with a require() statement.

// file2.js

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

You have defined myKeyPair in keys.js and not in op_return.js . If you need to define it in one file and use it in another, you need to define the variable as a global. Checkout the link below for global variables in node

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM