nev*_*ame 9 javascript global-variables node.js
我有3个节点文件:
// 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 Code Online (Sandbox Code Playgroud)
Run.js需要两个文件,需要模块并创建变量的modules.js,以及应该使用该变量的app.js.但我在app.js上收到错误导致app未定义.
有没有办法让这成为可能?
除非导出模块,否则模块中声明的所有内容都是该模块的本地模块.
可以从引用它的其他模块访问一个模块中的导出对象.
$ 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' }
Run Code Online (Sandbox Code Playgroud)
看起来您正在 module.js 中定义变量,但尝试在 app.js 中引用它。您需要在 app.js 中添加另一个 require:
// app.js
var application = require('./path/to/modules'),
app = application.app;
app.configure(...);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8513 次 |
| 最近记录: |