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.)
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)
Try NeDB: https://github.com/louischatriot/nedb
"Embedded persistent database for Node.js, written in Javascript, with no dependency (except npm modules of course). You can think of it as a SQLite for Node.js projects, which can be used with a simple require statement. The API is a subset of MongoDB's. You can use it as a persistent or an in-memory only datastore."
I found a library named json-fs-store to serialize JavaScript object to JSON in a file and retrieve it later.
When retrieving a file via the store.load
method (not described in the docs at the moment), it is parsed with JSON.parse
which is better than doing a require
like in the other answer:
- you get proper error handling when the contents are malformed
- if someone has managed to sneak JavaScript code into the file, it will lead to a parse error instead of the JS being executed.
If you are looking for performance consider: LokiJS
https://www.npmjs.com/package/lokijs
http://lokijs.org/#/