1

为了让我更清楚地了解我想要实现的目标。

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

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应该触发并执行任何已实施的操作。

4

1 回答 1

6

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

模块A:

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

模块B:

console.log(test);

将简单地输出undefined.

话虽如此,我认为这是您正在寻找的模块样式:

server.js:

var app = //instantiate express in whatever way you'd like
var loginApi = require('loginModule.js')(app);

登录模块.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 };
};

显然,调整以适应您的实际需求。有很多方法可以做相同类型的事情,但这与您的原始示例最接近。希望这会有所帮助。

于 2013-05-20T05:14:18.657 回答