André Kuhlmann André Kuhlmann - 6 months ago 7
Node.js Question

update global variable from a function inside a module

I tried to organize my project a bit, by creating different modules with different functions. But to be effective I need these functions to update my variables in my "app.js" file.

The code underneath should update and log the variable "name" as soon as I run the "myFunction" located in the "custom_module.js" file.
But what I get is:


Hello undefined


app.js

var name;
var module = require('./custom_module.js');
module.myFunction();
console.log("Hello " + name);


custom_module.js

var myFunction = function(){
name = "Test"
}

module.exports.myFunction = myFunction;


Does anyone knows how to solve this?

Answer

You could attach it to the global object... That's global in Node and window in the browser.

// app.js
window.name = 'Foo';

// custom_module.js
var myFunction = function(){
    window.name = "Bar";
}

P.S. Don't do this. Shared global variables are (usually) always evil.

Comments