0

I have a file called app.js:

let id = 0;
const Func = require('./func.js');
Func.myFunc();
console.log(id);


module.exports = {
     id 
};

Also I have another file called func.js:

const App = require('./app.js');
var myFunc = () => {
 App.id = 100;
}


module.exports = {
    myFunc
};

But console.log(id) returns: 0

developer
  • 170
  • 2
  • 12
  • One requires the other, and the other requires the one. Looks like you are on track for strange loop if this even works at all... Rethink your logic :) – Spangle Feb 04 '20 at 06:57
  • 2
    Two files can't `require()` each other (well they *can*, but not in the way you expect) – Jonas Wilms Feb 04 '20 at 06:57

3 Answers3

0

Add another log like:

 // app.js ...
 console.log(module.exports);
 module.exports = { id };
 console.log(id);

to see that your code does work somehow, in the way that module.exports has an id property set, but you override that afterwards. Also the property of the export object has nothing todo with the id variable (well, the later gets copied into the first) so console.log will never log 100.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

What you are doing is termed circular dependencies. It is generally frowned upon and there is no allowed instance where this may be required. You're better off creating a third file that will use both of them...

Read this to have a better understanding:

https://nodejs.org/api/modules.html#modules_cycles

How to deal with cyclic dependencies in Node.js

cross19xx
  • 3,170
  • 1
  • 25
  • 40
0

There are two problems with your piece of code:

  • the circular dependency
  • module.exports.id is not the same object as the variable id in app.js

In order to solve the first problem, you should create a third file where the variable will be declared and other modules will use that.

Now, to illustrate the second problem, look at the following.

// testModule.js
let variable = 0;

function get_variable() {
    return variable;
}

module.exports = {variable, get_variable};
// app.js
const testModule = require('./testModule.js');

testModule.variable = 1234;
console.log(testModule.variable);       // will print '1234'
console.log(testModule.get_variable()); // will print '0'

This little misunderstanding of modules, could lead to subtle nasty bugs. I consider that the best practice to solve this would be not to export the 'variable' property directly, but having getter/setter functions in the module, almost like transforming it into a class-like thing.

// testModule.js
let variable = 0;

function get_variable() {
    return variable;
}

function set_variable(value) {
    variable = value;
}

module.exports = {get_variable, set_variable};
Mihail Feraru
  • 1,419
  • 9
  • 17