Using a Flat-File Database in Node.js

In small-scale applications or scenarios where a full-fledged database management system might be overkill, using a flat-file database is a practical solution. In this article, we'll explore how to create, read, update, and delete (CRUD) data in a JSON file using Node.js.

What is a Flat-File Database?

A flat-file database is a database stored in a simple, plain-text file. In this example, we'll use a JSON file to structure and store our data. Each record or entry in the database corresponds to an object within the JSON file.

Setting Up the Database

Let's consider a basic example where we have a data.json file representing users and products:

{
  "users": [
    { "id": 1, "name": "John Doe", "age": 25 },
    { "id": 2, "name": "Jane Smith", "age": 30 }
  ],
  "products": [
    { "id": 101, "name": "Laptop", "price": 999.99 },
    { "id": 102, "name": "Smartphone", "price": 499.99 }
  ]
}

Reading and Writing Data

To perform CRUD operations, we can use the Node.js fs (File System) module. Here's a simple script that reads data from the file, modifies it, and writes it back:

const fs = require('fs');

// Read data from the file
const rawData = fs.readFileSync('data.json');
let data = JSON.parse(rawData);

// Create a new user
const newUser = { "id": 4, "name": "Bob", "age": 28 };
data.users.push(newUser);

// Update an existing user's age
const userIdToUpdate = 2;
const updatedUser = data.users.find(user => user.id === userIdToUpdate);
if (updatedUser) {
    updatedUser.age = 31;
} else {
    console.log('User not found.');
}

// Delete a user
const userIdToDelete = 1;
data.users = data.users.filter(user => user.id !== userIdToDelete);

// Write data back to the file
fs.writeFileSync('data.json', JSON.stringify(data, null, 2));

console.log('CRUD operations completed:', data);

This script demonstrates creating a new user, updating an existing user's age, and deleting a user from the users array.

Conclusion

Flat-file databases are a lightweight and straightforward solution for small applications or scenarios where simplicity is key. While suitable for certain use cases, larger or more complex applications may benefit from dedicated database management systems. Always consider the specific needs and scalability requirements of your project when choosing a database solution.

0
Subscribe to my newsletter

Read articles from Ogunuyo Ogheneruemu B directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ogunuyo Ogheneruemu B
Ogunuyo Ogheneruemu B

I'm Ogunuyo Ogheneruemu Brown, a senior software developer. I specialize in DApp apps, fintech solutions, nursing web apps, fitness platforms, and e-commerce systems. Throughout my career, I've delivered successful projects, showcasing strong technical skills and problem-solving abilities. I create secure and user-friendly fintech innovations. Outside work, I enjoy coding, swimming, and playing football. I'm an avid reader and fitness enthusiast. Music inspires me. I'm committed to continuous growth and creating impactful software solutions. Let's connect and collaborate to make a lasting impact in software development.