【问题标题】:How to pass properties into a require module?如何将属性传递给 require 模块?
【发布时间】:2023-04-02 09:38:01
【问题描述】:

在我的 index.js 中,我需要一个用于连接字符串等的 config 文件,如下所示:

var config = require('./config');

config.js 然后做:

module.exports = config;

所以在 index.js 中我可以使用像 config.db_connect_string 这样的属性关闭配置。

当我还需要例如 db.js 来执行数据库操作时,如何在 db.config 中创建的函数中访问 config 的属性并导出回index.js

希望这是有道理的!我从 node 开始。

【问题讨论】:

  • db.js 中,您还可以通过require('./config') 访问相同的值。不知道你还问什么。
  • 谢谢,我最终做到了——只是想知道 db.js 是否可以从 index.js 继承值
  • 否 - 没有“模块继承”。在另一个模块中访问数据的方式是使用require()

标签: node.js


【解决方案1】:

我不知道 db.js 长什么样,但是你应该可以将配置对象从你的 index.js 文件中注入到 db.js 模块中,然后使用柯里化函数来创建你想要的 db 对象导出。

像这样:

在 index.js 中

var config = require('./config');

var { makeDB } = require('./db');

var db = makeDB(config)

在 db.js

module.exports.makeDB =

    // Pass in the expected config object
    function(config) {

        // If your db module needs parameters
        // you can pass them in here
        return function(){

            // Create db module here.

            // The properties of the config object
            // passed in will be available here.

            // Be sure to return the database object.
            return db;
        }
    }

【讨论】:

    猜你喜欢
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 2016-02-28
    • 2017-12-25
    • 2018-08-31
    相关资源
    最近更新 更多