1

I'm new in Node.js and I wondering something. I'm use express and socket.io. there is some value to should be changeable, let's say this 'flag' that have boolean type variable - this is 'false' at default.

but some moment especially when I click some button, it would be change to 'true'. the express and socket.io workflow is fine, but I don't know how to modifying variable from different file not just copying it.

Please see below code to understand

Main.js

var flag = false;
exports.flag = flag; 

// display flag every second
setInterval((function(){console.log(flag)}), 1000);

Remote.js

// I want to change 'original flag' at main.js in remote.js 
// How can I do that? I think below is just copying it, so doesn't effect to main.js

flag = require('/Main').flag;

// the flag will be 'true' after some moment
flag = true;

expected result I want in main.js

false
false
false
...
true
true

How can I do that?

2 Answers 2

2

Have you tried using the included object instead of the property ?

That way you keep a reference on the object and not the primitive value.

main = require('/Main');

main.flag = true;

Edit : As said in the comment by Mike C, you would also need to use the object in the setInterval

setInterval((function(){console.log(exports.flag)}), 1000);

It works because Object is a reference type, compared to string or boolean which are primitive.

Sign up to request clarification or add additional context in comments.

2 Comments

They'd also have to change the code in main.js to use exports.flag in the setInterval.
Added more details :)
1

you can define a global variable and access is or change it wherever you want.

main.js

global.flag = false; 

// display flag every second
setInterval((function(){console.log(global.flag)}), 1000);

remote.js

// the flag will be 'true' after some moment
global.flag = true;

1 Comment

Thank you too, maybe this is easy way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.