在Javascript / node.js模块之间共享变量? [英] Share variables between modules in Javascript/node.js?
本文介绍了在Javascript / node.js模块之间共享变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有3个节点文件:
// run.js
require('。 /配置/模块);
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上得到一个错误,导致应用程序没有定义。
有没有办法让这成为可能?
从一个模块导出的对象
在一个模块中声明的所有东西都是本地模块,除非它被导出。可以从引用它的其他模块访问。
$ cat run.js
require('./ configurations /模块);
require('./ configurations / application');
$ cat配置/ modules.js
exports.somevariable = {
someproperty:'first property'
};
$ cat配置/ application.js
var modules = require('./ modules');
modules.somevariable.something ='second property';
console.log(modules.somevariable);
$ node run.js
{someproperty:'first property',
something:'second property'}
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?
解决方案
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' }
这篇关于在Javascript / node.js模块之间共享变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文