更改后如何将JSON文件重新加载为模块

时间:2019-08-19 10:44:26

标签: javascript node.js

我有一个配置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文件作为模块?

任何建议都值得赞赏。

1 个答案:

答案 0 :(得分: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);

在重新加载模块之前,只需添加一行以删除预加载的模块即可。