Why not write to a file?
// Writing...
var fs = require("fs");
var myJson = {
key: "myvalue"
};
fs.writeFile( "filename.json", JSON.stringify( myJson ), "utf8", yourCallback );
// And then, to read it...
myJson = require("./filename.json");
And remember that if you need to write-and-read repeatedly, you will have to clear Node's cache for each file you're repeatedly reading, or Node will not reload your file and instead yield the content that it saw during the first require
call. Clearing the cache for a specific require is thankfully very easy:
delete require.cache[require.resolve('./filename.json')]
Also note that if (as of Node 12) you're using ES modules rather than CommonJS, the import
statement does not have a corresponding cache invaldation. Instead, use the dynamic import(), and then because imports are from URL, you can add a query string as a form of cache busting as part of the import string.
Alternatively, to avoid any built-in caching, use fs.readFile()
/fs.readFileSync()
instead of require (using fs/promises
instead of fs
if you're writing promise-based code, either explicitly, or implicitly by using async/await)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…