为了让我更清楚地了解我想要实现的目标。
我有一台正在运行的服务器,其中包含许多模块,其中一个模块用于检查用户角色是否为管理员。
在 Server.js
var loginAPI = require('myModule')(argStringType),
express = require('express');
var app = express();
现在在 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 ) { };
};
从上面可以看出,我有两个函数,位于 module.exports
中他们工作得很好,除了 module.exports
之外的那个之外没有任何问题。如果我不尝试调用getContent
,那么这个就可以工作。 ,但这就是我想要实现的目标。当有人通过输入 URL
访问该网站时以该格式 app.get
应该火并做任何已实现的事情。
最佳答案
确保您意识到 Node.js 中的每个模块都有自己的作用域。所以
模块A:
var test = "Test output string";
require('ModuleB');
模块B:
console.log(test);
将简单地输出未定义
。
话虽如此,我认为这就是您正在寻找的模块样式:
服务器.js:
var app = //instantiate express in whatever way you'd like
var loginApi = require('loginModule.js')(app);
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 };
};
显然,请根据您的实际需要进行调整。有很多方法可以完成同一类型的事情,但这最适合您原来的示例。希望这会有所帮助。
关于node.js - 从同一文件 node.js 访问另一个 module.exports 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16639930/