You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js API定时更新共享配置问题:其他文件获取值始终为初始值

问题分析与解决方案

你的代码存在两个核心问题:

  1. 引用指向问题:你一开始导出的是空对象{}的引用,后续config = response是把config变量指向了一个新对象,但其他模块引入的还是最初那个空对象的引用,自然看不到更新。
  2. 异步操作未处理:fetch是异步函数,直接赋值response得到的是Promise对象,不是实际的配置数据。

修复后的代码示例

方案1:修改原对象属性(保持引用不变)

这种方式最直接,通过更新原对象的属性而非替换整个对象,让所有模块共享同一个引用:

const config = {};

async function refreshConfig() {
  try {
    const response = await fetch('你的配置接口地址');
    const newConfig = await response.json(); // 假设返回JSON格式
    // 清空原对象并赋值新属性
    Object.keys(config).forEach(key => delete config[key]);
    Object.assign(config, newConfig);
  } catch (e) {
    console.error('刷新配置失败:', e);
  }
}

// 立即执行一次初始化配置
refreshConfig();
// 定时刷新
setInterval(refreshConfig, 5 * 60 * 1000);

module.exports = config;

方案2:导出获取配置的函数

如果不想依赖对象引用,可以导出一个函数,每次调用都返回最新的配置:

let config = {};

async function refreshConfig() {
  try {
    const response = await fetch('你的配置接口地址');
    config = await response.json();
  } catch (e) {
    console.error('刷新配置失败:', e);
  }
}

refreshConfig();
setInterval(refreshConfig, 5 * 60 * 1000);

module.exports = () => config;

使用时需要调用函数获取最新值:

const getConfig = require('./config');
const currentConfig = getConfig();

方案3:使用ES6代理(进阶)

通过代理对象自动返回最新的配置,用法和直接引用对象一致:

let config = {};

async function refreshConfig() {
  try {
    const response = await fetch('你的配置接口地址');
    config = await response.json();
  } catch (e) {
    console.error('刷新配置失败:', e);
  }
}

refreshConfig();
setInterval(refreshConfig, 5 * 60 * 1000);

module.exports = new Proxy({}, {
  get(target, prop) {
    return config[prop];
  },
  set(target, prop, value) {
    config[prop] = value;
    return true;
  }
});

内容的提问来源于stack exchange,提问作者Football52

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 00:05:02