Home > Software engineering >  Module.exports returns undefined
Module.exports returns undefined

Time:07-21

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

CodePudding user response:

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

  • Related