Member-only story
How To Create a JSON Database In NodeJs From Scratch
In order to teach myself my ways of working with NodeJs, Javascript, and Typescript, I have built many versions of a file-based JSON database over the years, especially when I did not want to settle on a database setup for my project.
For this tutorial, I’ll show you how to put a file-based JSON database together quickly and enjoy every related algorithm. We will look into:
- Using file system module to read-write files;
- Create a powerful query API for the data;
- Handle data CRUD actions;
- Analyse ways to improve the data read-write performance;
Start a Typescript Node Project
I wrote a post on how to set up a Typescript Node project and shared it as a template you can clone and start a Node project. That’s the environment I will be using for this tutorial so simply run the following command to create your project:
git clone git@github.com:beforesemicolon/node-typescript-project-template.git
Make any necessary changes to the project and, let’s get going!
Implementation
I always start anything by walking backward from the developer experience. Then, I write the code for the behind-the-scenes to support those interactions. I call it DX-driven development.
I picture the database being started like so:
interface ToDo {
id: string,
name: string;
status: "pending" | "completed" | "archived";
user: {
name: string;
};
}
const db = new JSONDB<ToDo>("todo");
It should simply take the name of the JSON
file where all the data will be placed and take a generic type which should work like a schema of the data to help with the developer experience. The code behind this should look like so:
// src/db/JSONDB.ts
import path from "path";
import fs from "fs";
class JSONDB<T extends object> {
private readonly filePath: string;
constructor(private fileName: string) {
this.filePath = path.join(__dirname, `${fileName}.json`);
if (!fs.existsSync(this.filePath)) {
fs.writeFileSync(this.filePath, "[]", "utf-8");
}
}
}