gpt4 book ai didi

node.js - 如何将属性传递到 require 模块?

转载 作者:太空宇宙 更新时间:2023-11-04 01:55:31 25 4
gpt4 key购买 nike

在我的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 是什么样的,但您应该能够从 index.js 文件将配置对象注入(inject)到 db.js 模块中,然后使用柯里化(Currying)函数创建要导出的 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;
}
}

关于node.js - 如何将属性传递到 require 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48131727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com