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

标签 node.js module

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

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

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/

相关文章:

node.js - Froala 编辑器不适用于带有 typescript 的 Angular 4

javascript - 如何使用 Angularjs 在 URL 中没有 # 的单页应用程序?

javascript - Node.js 如何使用 this 和调用函数

javascript - 如何重复调用一个函数并等待完成后再调用下一次?

Python 自定义模块 - 示例代码出错

types - OCaml 类型/模块

node.js - Bot Framework 从 Cosmos DB 检索用户地址以发送主动消息 NODE JS

module - Puppet - 为非伪造模块安装模块依赖

python - 将模块重新导入 pycharm 控制台不会更新代码,除非我删除/重新启动控制台

Java源代码依赖关系图