简体   繁体   中英

Module.exports returns undefined

I'm trying to export a variable from a file, but when I require it in another I get undefined. I suspect my functions are causing it, but I'm not sure how to fix it.

Index.js:

app.post("/", (req,res) =>{ 
    console.log("Get from /");
    module.exports.SimpleMessage = 'Hello world';                 //exporting variable
    exec('npx hardhat run scripts/deploy.js --network goerli',
        (error, stdout, stderr) => {
            if (error !== null) {
                console.log(`exec error: ${error}`);
            }
        });
    res.send("Server received the request");
                            });

// starting the server
app.listen(3000, () => {
  console.log('listening on port 3000');
});

Deploy.js:

async function main() {
    const HelloWorld = await ethers.getContractFactory("HelloWorld");
 
    var msg = require('../src/index.js');                              //requiring variable
    console.log(msg.SimpleMessage);           

    const hello_world = await HelloWorld.deploy();   
 }

(Edit) This is the whole Deploy.js function:

async function main() {
    const HelloWorld = await ethers.getContractFactory("HelloWorld");
 
    var msg = require('../src/index.js');                              //requiring variable
    console.log(msg.SimpleMessage);           

    const hello_world = await HelloWorld.deploy();   
 }
 
 main()
   .then(() => process.exit(0))
   .catch(error => {
     console.error(error);
     process.exit(1);
   });

so there are a few things to unwrap over here:

  • your require() is probably invoked before module.exports.SimpleMessage = 'Hello world';- an easy issue to encounter when you deal with async functions

  • require() is implemented in such a way that if you call it twice with the same file, the second time around only the cached value is returned and so, if the value of SimpleMessage changes, you will not be able to import it any more. Instead only the original value will be returned.

A quick and simple solution is to export a value that will not change instead, like a function

let SimpleMessage;

module.exports.getSimpleMessage = () => SimpleMessage;

app.post("/", (req,res) =>{ 
    console.log("Get from /");
    SimpleMessage = 'Hello world';

    // and the rest of your logic
});

at this point you can reference getSimpleMessage that will be cached by require() but still will always return the updated version of SimpleMessage

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