简体   繁体   English

将选项传递到节点模块以供导出功能使用

[英]Passing options to node module for export functions to use

I am creating a node module and want the end user of this module to be able to pass it configuration options that will have an effect on the modules functions. 我正在创建一个节点模块,希望该模块的最终用户能够通过它的配置选项,这些配置选项会对模块功能产生影响。

For example, with express you can create an express app and pass it to your routes as such: 例如,使用express可以创建一个express应用并将其传递到您的路线,例如:

const express = require('express');
const app = express();

require('./api/routes/login)(app)

and then in your routes file you can use that app -> /api/routes/login 然后在您的路线文件中,您可以使用该应用-> / api / routes / login

//login.js

  module.exports = function(app){

   app.get('/login', function(req, res){//blah}

  }

So what I am trying to do in my module is something similar in which an end user can pass an optional config parameters for the module's functions to use. 因此,我试图在模块中执行的操作与之类似,最终用户可以传递可选的配置参数以供模块功能使用。 This is was I was trying..... 这是我正在尝试的.....

In my module file: 在我的模块文件中:

const default_options = {"enabled":true}
module.exports = function(options) {
const options = options || default_options

exports.login = function(credentials) {
if(options.enabled == true){
 //do something
 }else{
    //do something else
  }
 }

}

And then someone using the module would be able to do something like this: 然后使用该模块的人将可以执行以下操作:

//some js file
 var options = {"enabled":false}
 const mod = require('mymodule')(options)

 mod.login(creds)

The error I am getting is 'Cannot read property 'login' of undefined'. 我收到的错误是“无法读取未定义的属性”登录名”。 I suspect it has something to do with me using exports twice but trying to figure out how to structure my module's js file to be able to use these options if passed it and apply them to the exposed functions. 我怀疑使用两次导出与我有关,但是试图弄清楚如何构造模块的js文件,以便在传递这些选项时能够使用这些选项并将其应用于公开的函数。

Any help is appreciated, thank you! 任何帮助表示赞赏,谢谢!

You need to return an object from the exported function. 您需要从导出的函数返回一个对象。

const default_options = {"enabled":true}
module.exports = function(options) {
    const options = options || default_options
    return {
        login: function(credentials) {
            ...
        }
    }
}

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

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