繁体   English   中英

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

[英]Access another module.exports function from the same file node.js

为了使我要达到的目标更加清楚。

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

Server.js

   var loginAPI = require('myModule')(argStringType),
       express = require('express');

   var app = express();

现在,在myModule.js我已经实现了几个功能,只想添加一个功能,但是实际上不需要从server.js调用此功能,而是在用户访问该URL立即调用该功能。 ,所以我想在myModule.js添加类似的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 ,则该module.exports可以正常工作。但这就是我要实现的目标。 当有人通过以该格式输入URL来访问站点时, app.get应该很火,并且可以执行实现的所有操作。

确保您意识到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);

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM