Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

javascript - Easy way to store JSON under Node.js

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

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

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...