Share variables between files in Node.js?

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;

Leave a Comment