从同一个文件node.js访问另一个module.exports函数

为了让我更清楚一点,我试图实现。

我有一个运行的服务器,其中包含许多模块,其中一个模块用于检查用户angular色是否是pipe理员。

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 ,除了模块之外,没有任何问题。只要我不尝试调用getContent ,但是这是我想要实现的。 当有人通过以这种格式inputURL访问网站时, app.get应该被触发,并执行任何被执行的操作。

确保你认识到Node.js中的每个模块都有自己的范围。 所以

ModuleA:

 var test = "Test output string"; require('ModuleB'); 

ModuleB:

 console.log(test); 

将简单的输出undefined

有了这个说法,我认为这是你正在寻找的模块的风格:

server.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 }; }; 

显然,适应你的实际需要。 有很多方法可以做同样的事情,但是这与你最初的例子最接近。 希望有帮助。