André Kuhlmann André Kuhlmann - 1 year ago 101
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


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


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

module.exports.myFunction = myFunction;

Does anyone knows how to solve this?

Answer Source

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

// app.js = 'Foo';

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download