为了使我想要实现的目标更加明确.
我有一个运行的服务器,其中包含许多模块,其中一个模块用于检查用户角色是否为管理员.
在 Server.js
var loginAPI = require('myModule')(argStringType),
express = require('express');
var app = express();
Run Code Online (Sandbox Code Playgroud)
现在,myModule.js我已经实现了很少的功能,只想添加一个,但是这个功能真的不需要调用,server.js而是一旦人们访问就会调用URL,所以我想添加一些东西喜欢这个myModule.js
在 myModule.js
app.get( "/post/:postid", function( req, res ) {
var id = req.param('postid');
return getContent( postid );
});
// Module.exports
module.exports = function ( arg ) {
return {
getContent: function ( id ) { },
getHeader: function ( id ) { };
};
Run Code Online (Sandbox Code Playgroud)
所以你可以从上面看到,我有两个功能,module.exports并且他们工作正常没有问题,除了module.exports那个工作之外,如果我不试图打电话getContent,但这就是我的意思试图实现.当某人通过输入该URL格式访问该网站时,app.get应该开火并执行任何实施的操作.
确保您意识到Node.js中的每个模块都有自己的范围.所以
ModuleA:
var test = "Test output string";
require('ModuleB');
Run Code Online (Sandbox Code Playgroud)
ModuleB:
console.log(test);
Run Code Online (Sandbox Code Playgroud)
将简单输出undefined.
话虽如此,我认为这是您正在寻找的模块风格:
server.js:
var app = //instantiate express in whatever way you'd like
var loginApi = require('loginModule.js')(app);
Run Code Online (Sandbox Code Playgroud)
loginModule.js:
module.exports = function (app) {
//setup get handler
app.get( "/post/:postid", function( req, res ) {
var id = req.param('postid');
return getContent( postid );
});
//other methods which are indended to be called more than once
//any of these functions can be called from the get handler
function getContent ( id ) { ... }
function getHeader ( id ) { ... }
//return a closure which exposes certain methods publicly
//to allow them to be called from the loginApi variable
return { getContent: getContent, getHeader: getHeader };
};
Run Code Online (Sandbox Code Playgroud)
显然,调整以适应您的实际需求.有很多方法可以做同样类型的事情,但这与你原来的例子最接近.希望这会有所帮助.
| 归档时间: |
|
| 查看次数: |
5837 次 |
| 最近记录: |