Building Your own Simple JSON Database

Building Your own Simple JSON Database

Building Your own Simple JSON Database with Ezhill Ragesh

Introduction

So What exactly is a Database?

Databases are like digital filing cabinets. They help store and organize information in a structured way, making it easy to find and manage data. From tracking your online shopping history to storing usernames and passwords securely, databases quietly handle the behind-the-scenes work, ensuring our digital experiences run smoothly. They’re the unsung heroes of the data world, quietly doing their job to keep things organized and accessible.

Now What is JSON?

JSON, or JavaScript Object Notation, is a lightweight and readable way for computers to exchange information. Think of it as the language data speaks when computers want to share notes. With its human-readable format and versatility, JSON has become a go-to choice for representing data structures in web development. It’s like the universal translator, allowing different systems to understand and communicate effortlessly.

A sample JSON by Ezhill Ragesh

In this JSON example, we have information about a student named Ezhill Ragesh. The data includes details such as the student’s name, title , and the year of study. This simple structure showcases how JSON neatly organizes data for easy interpretation and utilization in various applications.

Together, databases and JSON form a dynamic duo, simplifying how we handle, store, and interact with data in the vast digital landscape.

Working with Your Simple JSON Database:

Step 1: Reading Data

Our database starts with reading data. Using the readDB function, we can fetch information effortlessly. For instance, consider a scenario where we want to retrieve details about a student. A simple call like readDB('students.json') brings the stored data to our fingertips.

Step 2: Writing Data

When it’s time to add new information, the writeDB function comes into play. It's like adding a new book to our digital library. Just provide the data and the file name, and voila—your database is updated. For example, writeDB(newStudentData, 'students.json') seamlessly incorporates fresh details into our database.

Step 3: Updating Records

As time goes by, information might need tweaking. That’s where the updateDB function shines. Need to change a student's title or update the year? A quick call like updateDB(updatedStudentData, 'students.json') takes care of the modifications.

Start Building Now!

1. Importing Required Module

const fs = require(‘fs’);

This block imports the File System (fs) module, a core module in Node.js used for file-related operations. It's essential for reading and writing data to files in Node.js .

2. Reading Data from JSON Database

function readDB(nameDB) {
    try {
        const data = fs.readFileSync(nameDB, 'utf8');
        return JSON.parse(data);
    } catch (err) {
        console.error("Failed to read data:", err);
        return null;
    }
}
  • This block defines a function named readDB responsible for reading data from the JSON database file.

  • It uses fs.readFileSync to read the file synchronously, and JSON.parse is employed to convert the file content (in JSON format) into a JavaScript object.

  • Error handling is implemented using a try-catch block. If there's an error (e.g., file not found or invalid JSON), it logs an error message and returns null.

3 . Writing Data to JSON Database

function writeDB(data, nameDB) {
    if (!data) return console.log('No data Found');
    try {
        fs.writeFileSync(nameDB, JSON.stringify(data));
        console.log("Data Saved");
    } catch (err) {
        console.error("Failed to write data:", err);
    }
}
  • This block defines a function named writeDB responsible for writing data to the JSON database file.

  • It checks if the provided data is truthy. If not, it logs a message and exits the function.

  • It uses fs.writeFileSync to write the data to the file. JSON.stringify converts the data to a JSON string with indentation for better readability (null, 2).

  • Error handling is implemented, logging an error message if there’s an issue during the write operation

4. Updating Records in JSON Database

function updateDB(updatedRecord, nameDB, uniqueIdentifier = 'id') {
    const existingData = readDB(nameDB);

    if (!existingData) {
        console.error('No existing data found.');
        return;
    }
    const indexToUpdate = existingData.findIndex(record => record[uniqueIdentifier] === updatedRecord[uniqueIdentifier]);

    if (indexToUpdate === -1) {
        console.error('Record not found for update.');
        return;
    }
    existingData[indexToUpdate] = { ...existingData[indexToUpdate], ...updatedRecord };
    writeDB(existingData, nameDB);
}
  • This block defines a function named updateDB responsible for updating records in the JSON database.

  • It first reads the existing data using the readDB function.

  • Error handling checks if there is existing data. If not, it logs a message and exits the function.

  • It finds the index of the record to update based on the unique identifier (default is ‘id’) using findIndex.

  • If the record is not found, it logs an error message and exits.

  • It updates the existing record with the new data using the spread operator (...).

  • The updated data is then written back to the database using the writeDB function.

Now we need to export the functions.

5. Exporting the Module

module.exports = { readDB, writeDB, updateDB };

A sample code where I use the JSON database by ezhill ragesh

In this example script, we interact with our simple JSON database using the functions provided in dbMain.js. We start by reading existing data from the 'db.json' file and display it. Then, we add a new student record, writing it to the database and reading the updated data to showcase the modification. Next, we update a specific student's title to demonstrate the functionality of the update operation. Finally, we read the data again after the update to observe the changes. This script exemplifies the seamless utilization of our JSON database module for reading, writing, and updating data, showcasing the practicality and simplicity of the implemented functionalities.

Stay Connected:

Don’t hesitate to share your thoughts, ask questions, and contribute to the discussion.

Happy coding!