【问题标题】:How to reload JSON file as module after change it更改后如何将 JSON 文件重新加载为模块
【发布时间】:2019-12-24 13:56:05
【问题描述】:

我有一个配置 JSON 模块 config.json 像:

{
    "comment": "This is old config"
}

我使用require('./config.json') 将其作为模块导入。在我的源代码中,我想更新 JSON 文件的内容并像新内容一样重新加载它:

{
    "comment": "This is new config"
}

例如,在index.js 中,我将重写config.json 文件并重新导入,如下所示:

const fs = require("fs");
const path = require("path");
let config = require("./config.json");

console.log('Old: ' + config.comment);

// Rewrite config
let newConfig = {
  comment: "This is new config"
};

fs.writeFileSync(
  path.join(process.cwd(), "config.json"),
  JSON.stringify(newConfig, null, "\t")
);

// Reload config here
config = require("./config.json");
console.log('New: ' + config.comment);

控制台的输出:

Old: This is old config
New: This is old config

我看到 JSON 内容更新了,但我无法重新加载模块,config 变量仍然包含之前相同的缓存数据。如何将 JSON 文件作为模块重写和重新导入?

欢迎提出任何建议。

【问题讨论】:

  • @ambianBeing 但您的参考资料没有提供答案?
  • 更新config.json后尝试使用require('./config.json')
  • 所以您使用 json 文件作为数据并且当该文件更改时您想重新读取该数据?或者当你重建时你想重新加载模块? require(ing) 如果它是数据,那么它是错误的做法。旨在加载源代码,除非您重新运行源代码,否则它不会改变。
  • @ThanhPhan 因为节点中的 AFAIK 模块解析是通过依赖路径(相对/绝对)发生的,并且在后台 require 使用 require.resolve() 其中生成的 cache 字典包含 key 作为 @ 987654338@。这就是为什么我们必须通过路径解析和删除。如果该断言是错误的,请(任何人)纠正我。

标签: javascript node.js


【解决方案1】:
const fs = require("fs");
const path = require("path");
let config = require("./config.json");

console.log('Old: ' + config.comment);

// Rewrite config
let newConfig = {
  comment: "This is new config"
};

fs.writeFileSync(
  path.join(process.cwd(), "config.json"),
  JSON.stringify(newConfig, null, "\t")
);

// Reload config here
delete require.cache[require.resolve('./config.json')]   // Deleting loaded module
config = require("./config.json");
console.log('New: ' + config.comment);

刚刚添加了一行删除预加载的模块,然后重新加载它。

【讨论】:

    猜你喜欢
    • 2016-01-24
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多