Filesystem JSON (de)serialization with Node.js

November 18, 2014

Here's a wicked simple way to read and write JavaScript objects to disk for situations where a database would be overkill.

First, import the fs module:

var fs = require('fs')

Define a function to synchronously save an object to disk as a JSON string:

function write(x) {
  var json = JSON.stringify(x, null, 2)
  fs.writeFileSync("db.json", json)
}

Define a function to synchronously load the JSON string from disk and return it as a JavaScript object:

function read() {
  var s = fs.readFileSync("db.json")
  return JSON.parse(s)
}

Now it can be put to use as a poor man's database:

var date = new Date()
var data = {
    date: date
  , foo: 'foo ' + date.toString()
  , bar: 'bar ' + date.toString()
}

write(data)

console.log(read())