I have a configuration JSON module config.json
like:
{
"comment": "This is old config"
}
I'm using require('./config.json')
to import it as a module. Some where in my source code, I want to update the content of JSON file and reload it like new content:
{
"comment": "This is new config"
}
For example, in index.js
I will rewrite config.json
file and reimport it like below:
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);
Console's output:
Old: This is old config
New: This is old config
I saw JSON content updated, but I cannot reload module, config
variable still contains the same cache data before. How can I rewrite and reimport JSON file as module?
Any suggestion is appreciated.