【问题标题】:require a module from within another module errors需要另一个模块中的模块错误
【发布时间】:2017-01-27 17:27:09
【问题描述】:

我是一名业余的 nodejs 开发人员。我在使用 javascript 模块时遇到严重问题,并且需要来自其他模块内部的模块。这是我需要帮助的场景。

假设我在一个文件中有 API 定义,例如 (userApi)

var userFunctions = require('./userFunctions.js')()

module.exports = function(){

module.getUser = function(req.res){
    userFunctions.getUser(req.id, function(err,user){
      if(err) return res(err)
      return res(null,user)
    })
}

return module;
}

这样的辅助模块 (userFunctions.js)

var paymentFunctions = require('../payment/paymentFunctions.js')()

module.exports = function(){
module.getUser = function(id,res){
//logic
}
return module;
}

另一个类似这样的辅助模块(paymentFunctions.js)

var userFunctions = require('../user/userFunctions.js')()

module.exports = function(){
  module.makePayment = function(req,res){
    userFunctions.getUser(req.id, function(err){
      if(err) return res(err)
      return res(null)
    })
  }
return module;
}

如您所见,我所有的助手和 API 都在模块中。我还在 require 语句的末尾加上括号。您可能还注意到 paymentFunctions 需要 userFunctions ,反之亦然。在我使用 node 期间,我还没有弄清楚这种模式带来的各种错误。今天我看到“要求不是函数错误”。注意:当我重新索引我的 webstorm 项目时,它正在工作并突然停止工作。话虽如此,我过去在 require 语句和 JS 模块方面遇到过许多类似的错误。因此,这是一个更系统性的问题,我需要在我的大脑中解决。

【问题讨论】:

    标签: javascript node.js express-4


    【解决方案1】:

    好吧,我认为秘诀在于了解 module.exports 的工作原理。首先,您需要创建一个“可导出”对象,然后设置其属性和方法。

    类似:

    var userFunctions = require('./userFunctions.js');
    //Lets say this is your userApi class
    module.exports = function () {
        this.getUser = function (req, res) {
            userFunctions.getUser(req.id, function (err, user) {
                if (err) return res(err)
                return res(null, user)
            });
        }
    };
    

    在这种情况下,我创建了一个对象(实际上是一个“Javascript 类”)并将其导出为一个模块。然后,我可以在代码的其他地方要求它和它的方法,因为这个属性是在可导出对象上设置的(this.prop = ...)。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-30
    • 2012-07-09
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    相关资源
    最近更新 更多