Share variables between files in Node.js?

never_had_a_name picture never_had_a_name · Oct 13, 2010 · Viewed 201.4k times · Source

Here are 2 files:

// main.js
require('./modules');
console.log(name); // prints "foobar"

// module.js
name = "foobar";

When I don't have "var" it works. But when I have:

// module.js
var name = "foobar";

name will be undefined in main.js.

I have heard that global variables are bad and you better use "var" before the references. But is this a case where global variables are good?

Answer

jmar777 picture jmar777 · Oct 13, 2010

Global variables are almost never a good thing (maybe an exception or two out there...). In this case, it looks like you really just want to export your "name" variable. E.g.,

// module.js
var name = "foobar";
// export it
exports.name = name;

Then, in main.js...

//main.js
// get a reference to your required module
var myModule = require('./module');

// name is a member of myModule due to the export above
var name = myModule.name;