0

I am following the Example listed out by: Share variables between files in Node.js?

main.js:

var name = "foobar";
exports.name = name;
var Login = require("./Scripts/file");

file.js:

 const file = require('./../main.js');
 var name = file.name;
 console.log("result: "+name);

output:

result: undefined

when I adjust file.js:

const file = require('./../main.js');
var name = file.name;

setInterval(function(){
    console.log("result: "+name);

},1000/30);

output:

result: foobar

It looks like the variable is being passed late? how do I prevent this?

MoonEater916
  • 436
  • 2
  • 6
  • 19
  • What's the point of this circular import? What are you trying to accomplish here? – ggorlen May 17 '20 at 04:52
  • You have a circular `require()` where A loads B and B loads A. Can't do that in node.js. One of the `requires()` will end up not getting its exports because of the circularity. – jfriend00 May 17 '20 at 05:13
  • Exporting variable from main.js to file.js. Program entry point is main.js So i am using require to ensure that file.js is running also but it also needs variable passed to it from main.js. I assume this is not good programming? – MoonEater916 May 17 '20 at 05:49
  • Move common dependencies to a 3rd file so that A loads C and B loads C. This breaks the circular dependency. – jfriend00 May 17 '20 at 08:52

0 Answers0