Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share variables between modules in Javascript/node.js?

I have 3 node files:

// run.js

require('./configurations/modules');
require('./configurations/application');

// modules.js

var express = module.exports.express = require('express');
var app = module.exports.app = express.createServer();

// app.js

app.configure(...)

Run.js requires both files, modules.js which require a module and creates a variable, and app.js which should use that variable. But I get an error on app.js cause app isn't defined.

Is there a way to make this possible?

like image 498
never_had_a_name Avatar asked Oct 12 '10 23:10

never_had_a_name


1 Answers

Everything declared in a module is local to that module unless it is exported.

Exported objects from one module can be accessed from other modules that reference it.

$ cat run.js 
require('./configurations/modules');
require('./configurations/application');

$ cat configurations/modules.js 
exports.somevariable = {
  someproperty: 'first property'
};

$ cat configurations/application.js 
var modules = require('./modules');

modules.somevariable.something = 'second property';
console.log(modules.somevariable);

$ node run.js 
{ someproperty: 'first property',
  something: 'second property' }
like image 81
Fernando Correia Avatar answered Nov 08 '22 20:11

Fernando Correia