JSON as flat file database

JSON is the best possible solution for the flat file database system.

JSON is really easy to read and write back to the disk. You need basic javascript knowledge to understand JSON file. You can use JSON in any platform and with a y language. Here we will check NodeJS example for reading and writing data to databse.

JSON file will look like as below in the nut sell.

{
    "id": 1
    "name": "CodeRecharge.",
    "likes": 12,
    "visits": 1000
}

Here we will check very easy implementation which is based on node js. To read and write JSON file in node js you can use const fs = require(‘fs’) filesystem module.

Read the JSON file as flat file database

const fs = require("fs");
const fileContents = fs.readFileSync("./database.json", "utf8");
const dtabaseObject = JSON.parse(fileContents);

console.log(dtabaseObject.name);

// output : CodeRecharge.

Now lets say we need to increase like of the site. we need to basically add integer number to the likes field. This will require 2 operation read the file and write it bake to the file system

Write the JSON file as flat file database


// read
const fs = require("fs");
const fileContents = fs.readFileSync("./database.json", "utf8");
const databaseObject = JSON.parse(fileContents);

// write
const fs = require("fs");
const fileContents = fs.readFileSync("./database.json", "utf8");
const databaseObject = JSON.parse(fileContents);

// modify our dtaObject
databaseObject.likes = databaseObject.likes + 1;
fs.writeFileSync("./database.json", JSON.stringify(databaseObject, null, 2));

// now next time if you read databaseObject.likes it will be increased.

In this way you can read and write to JSON file wothout any issue. If you check this code its really easy to undestand and write.

If you wondering for very small site and infomrative site is it feasible. Yes its definitely.

You can also add minor features like like of the pages, bookmark etc..

Fun fact is that we do not need any third-party library to manage this JSON files you can just use nodejs native filesystem library for this.

In next article we can check how we can manage relational fields in JSON.

Related Articles

js interview questions