Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm looking for a super-simple way to store one JSON array in a persistent way under Node.js. It doesn't need to have any special features. I just want to put a JSON object in there and be able to read it at the next server restart.

(Solutions like MongoDB and CouchDB both seem like overkill for this purpose.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
178 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...