Edward Gizbreht
Edward Gizbreht

Reputation: 306

Node js, function execution

i have a question about the node js execution of function. Code example

const dynamic = require('dynamic'),
      obj1 = dynamic.obj1,
      ovj2 = dynamic.obj2;

const myFunction1 = () => {
      let x = obj1  
      };

const myFunction2 = () => {
      let x = obj2  
      };

module.exports.myFunction1 = myFunction1;
module.exports.myFunction2 = myFunction2;

The question is how to design this code to able get updated value from dynamic variable every time when i calling myFunctions. Because require works only once, in the beginning of module. And the dynamic would be static, how to make a solution for it?

Upvotes: 0

Views: 87

Answers (2)

Lazyexpert
Lazyexpert

Reputation: 3164

This should work as you expect:

const dynamic = require('dynamic');

const myFunction1 = () => {
  const x = dynamic.obj1;
};

const myFunction2 = () => {
  const x = dynamic.obj2;
};

module.exports.myFunction1 = myFunction1;
module.exports.myFunction2 = myFunction2;

Upvotes: 1

Łukasz Szewczak
Łukasz Szewczak

Reputation: 1881

If you are the owner of the dynamic module you can change it to export function from this module not an object, thanks to this caching mechanism of the require method wont be a problem. Then you can just call function from this module in every place in module, and values can be retrived updated

//  dynamic.js
module.exports = () => {

  return {
    obj1,
    obj2
  };
};


//and in another module
const dynamic = require('dynamic'),
  // then in code you can do this
  obj1 = dynamic().obj1,
  ovj2 = dynamic().obj2;

Upvotes: 1

Related Questions