Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.)

like image 428
johnny Avatar asked Feb 18 '13 15:02

johnny


People also ask

How do I save JSON data in node JS?

To save the JSON object to a file, we stringify the json object jsonObj and write it to a file using Node FS's writeFile() function.

What is the best way to store JSON?

LOB storage - JSON documents can be stored as-is in NVARCHAR columns. This is the best way for quick data load and ingestion because the loading speed is matching loading of string columns.

How do I write a JSON object to a file in node JS?

Write JSON to File You can use the JSON. stringify() method to convert your JSON object into its string representation, and then use the file system fs module to write it to a file. Be careful when you use synchronous file operations in Node. js.


2 Answers

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)

like image 196
gustavohenke Avatar answered Sep 22 '22 21:09

gustavohenke


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."

like image 37
Ray Hulha Avatar answered Sep 23 '22 21:09

Ray Hulha