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 an JSON object in there and be able to read it at the next server restart. Mongo.db or Couch.db seem like an 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");

I found a library named node-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.

You could just save the JSON-data in a simple textfile and read it at server restart.

require('yourarrayfile.json')

and then work with it as usual.

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