【问题标题】:Node ( Express ) file import into controllers节点 ( Express ) 文件导入控制器
【发布时间】:2020-01-30 05:32:35
【问题描述】:

在我的 express 应用程序中,我有一个 methods 目录,其中包含 methods.js 文件,我在其中编写了需要在每个控制器中使用的非常常用的函数。

methods.js

function helloworld() {
    return "Hello World"
}

现在我需要将文件添加到我的控制器文件中,并且我需要使用该功能..

我试过了

const Methods = require('../methods/methods')

exports.passengerStatus = (req, res) => {
    let x = Methods.helloworld()
    console.log(x)
}

路由被调用,但错误是

 Methods.helloworld() is not define

如何将文件导入控制器?有什么方法可以导入文件,这样我就可以在不导入控制器的情况下访问文件方法。

【问题讨论】:

    标签: node.js express ecmascript-6


    【解决方案1】:

    你可以编写methods.js如下

    var commonFunctions = {};
    
    commonFunctions.sample = function(){
       // Write your code here
    };
    
    // Add other functions as sample here
    
    
    module.exports = commonFunctions;
    

    【讨论】:

    • 酷。有什么办法可以全局导入文件。这样我就可以在不导入文件的情况下访问这些功能?
    • 目前无法全局导入文件。
    【解决方案2】:

    你也可以这样写

    method.js

      function helloWorld() {
    
        return "hello method";
    }
    
    function mySecondMethod() {
    
        return "hello my second method";
    }
    
    function myThirdMethod() {
    
        return "hello my third method";
    }
    
    module.exports = {
        helloWorld,
        mySecondMethod,
        myThirdMethod
    }
    

    constroller.js

     let { helloWorld,mySecondMethod,myThirdMethod } = require("./method.js");
    console.log(helloWorld);
    console.log(mySecondMethod);
    console.log(myThirdMethod);
    

    【讨论】:

    • 我在文件中有数百个函数。我应该按照您的要求导出所有功能吗?
    • 是的,这可能是可能的。请查看更新的代码。
    猜你喜欢
    • 2015-09-26
    • 1970-01-01
    • 2020-10-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    • 2018-03-12
    相关资源
    最近更新 更多