Search code examples
javascriptnode.jsasynchronouscommonjs

Changing variable value in module with async function and than importing in other one


I have a problem with reading the variable from a file, which changes it with the promise function.

I have two modules:

  • one that exposes configuration, and obtains mac address from the device, the app is running on
  • one that consumes the configuration

Example

config.js

// some imports

let currentMacAddress;
(async () => {
    currentMacAddress = await toMAC(cameraIp);
    console.log(currentMacAddress) // works, sets mac address as expected
})();

module.exports = {
    currentMacAddress,
}

somefile.js

const { currentMacAddress } = require('./config.js')

console.log(currentMacAddress) // undefined

setTimeout(() => console.log(currentMacAddress), 10000) // undefined, the timeout is enough for this operation

I believe this is because require does import only one time, so it sets the variable with the value of currentMacAddress which is undefined and that's it.

How can I persist the value in currentMacAddress so that any other module could access its updated value?


Solution

  • Make the currentMacAddress a property of the exported object:

    const config = {currentMacAddress: undefined};
    (async () => {
      config.currentMacAddress = await toMAC(cameraIp);
    })();
    module.exports = config;
    

    And import it without deconstructing:

    const config = require('./config.js')
    console.log(config.currentMacAddress)
    setTimeout(() => console.log(config.currentMacAddress), 10000)