2010-10-12 105 views
9

我有3个节点文件:在Javascript/node.js模块之间共享变量?

// 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需要两个文件,这需要一个模块,并创建一个变量modules.js和app.js应使用该变量。但是我在app.js上得到一个错误,导致应用程序没有被定义。

有没有办法让这成为可能?

回答

0

它看起来像你在modules.js中定义变量,但试图在app.js中引用它。您需要在app.js中有另一个需求:

// app.js 
var application = require('./path/to/modules'), 
    app = application.app; 

app.configure(...); 
8

除非导出,否则在模块中声明的所有内容都是该模块的本地内容。

从一个模块导出的对象可以从引用它的其他模块访问。

$ 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' }