JSON User Database in Node.js
In Node.js, we can use JSON files to store and manage user information. We can add new users, retrieve existing users, search for a particular user, update user details, and delete unwanted records.
In this tutorial, we will build a complete file-based user management application using JavaScript, JSON, and Node.js built-in modules.
1. What Is a JSON User Database?
A JSON user database is a structured collection of user records stored in a JSON file. Each record contains properties such as user ID, name, email address, and city.
For example, a training institute may want to maintain student information. Each student can be stored as an object, and all student objects can be stored inside a JSON array.
Example: Student Records
[
{
"id": 1,
"name": "Samadhan",
"email": "samadhan@example.com",
"city": "Pune"
},
{
"id": 2,
"name": "Pradnya",
"email": "pradnya@example.com",
"city": "Mumbai"
}
]
In this example:
iduniquely identifies a record in this example.namestores the user's name.emailstores the user's email address.citystores the user's city.
2. How Does JSON File Storage Work?
A JSON file stores data as text. Node.js reads that text, converts it into JavaScript data, performs an operation, and writes the updated data back to the file.
User requests an operation
Use the fs module
JSON.parse() creates JavaScript data
Add, search, update, or delete a user
JSON.stringify() and fs.writeFileSync()
Important Modules
| Module | Purpose |
|---|---|
fs |
Reads, creates, and writes files. |
path |
Builds file paths in a platform-friendly way. |
JSON.parse() |
Converts JSON text into JavaScript data. |
JSON.stringify() |
Converts JavaScript data into JSON text. |
3. Create the Project Structure
First, create a folder named JsonUserDatabase.
Inside that folder, create the following two files.
JsonUserDatabase/
|
|-- app.js
|
|-- users.json
Step 1: Create users.json
Add an empty array to the file. An empty array means that no user records have been stored yet.
[]
Step 2: Import the Modules
const fs = require("fs");
const path = require("path");
require("fs") loads the built-in file system module.
require("path") loads the module that helps construct
file paths.
We can then create the path to our JSON file:
const filePath = path.join(__dirname, "users.json");
__dirnamerepresents the directory containing the current script.path.join()combines the directory and file name.filePathstores the resulting path.
4. Read Data from the JSON File
Before adding or modifying users, we need to read the current
records from users.json.
function readUsers() {
const data = fs.readFileSync(filePath, "utf8");
const users = JSON.parse(data);
return users;
}
Understanding the Code
readFileSync()reads the file contents."utf8"tells Node.js to return the content as text.JSON.parse(data)converts the JSON text into a JavaScript value.return userssends the resulting array back to the calling function.
Example
const users = readUsers();
console.log(users);
If the file contains an empty array, the output is:
[]
5. Save Data into the JSON File
After changing a user's information, we need to save the updated array back into the file.
function writeUsers(users) {
const jsonData = JSON.stringify(users, null, 2);
fs.writeFileSync(filePath, jsonData);
}
What Does JSON.stringify() Do?
It converts JavaScript data into JSON text. The second argument
can be used to select properties; here it is null.
The third argument, 2, adds two-space indentation
to make the file easier to read.
Example
const users = [
{
id: 1,
name: "Samadhan",
email: "samadhan@example.com",
city: "Pune"
}
];
writeUsers(users);
The file will contain:
[
{
"id": 1,
"name": "Samadhan",
"email": "samadhan@example.com",
"city": "Pune"
}
]
6. CRUD Operations
CRUD is a common term used in software development to describe four basic data operations.
| Operation | Meaning | Example |
|---|---|---|
| Create | Add a new record. | Add a student. |
| Read | Retrieve existing records. | Display all students. |
| Update | Modify an existing record. | Change a student's city. |
| Delete | Remove a record. | Delete a student. |
7. CREATE — Add a New User
The Create operation adds a new user object to the array and saves the updated array in the JSON file.
function addUser(name, email, city) {
const users = readUsers();
const newId = users.length > 0
? Math.max(...users.map(user => user.id)) + 1
: 1;
const newUser = {
id: newId,
name: name,
email: email,
city: city
};
users.push(newUser);
writeUsers(users);
console.log("User added successfully:", newUser);
}
Explanation
readUsers()retrieves the current records.map()collects existing IDs so the next ID can be calculated.Math.max()finds the highest existing ID.users.push()adds the new object to the array.writeUsers()saves the updated array.
Calling the Function
addUser(
"Samadhan",
"samadhan@example.com",
"Pune"
);
Example output:
User added successfully: {
id: 1,
name: 'Samadhan',
email: 'samadhan@example.com',
city: 'Pune'
}
8. READ — Display All Users
The Read operation retrieves all records from the file and displays them in the terminal.
function getAllUsers() {
const users = readUsers();
console.log("All Users:");
console.log(users);
}
Calling the Function
getAllUsers();
Example output when two users exist:
All Users:
[
{
id: 1,
name: 'Samadhan',
email: 'samadhan@example.com',
city: 'Pune'
},
{
id: 2,
name: 'Pradnya',
email: 'pradnya@example.com',
city: 'Mumbai'
}
]
The output is a JavaScript array containing objects. The exact formatting shown in the terminal can vary.
9. SEARCH — Find a User by ID
Sometimes we need one particular user instead of the complete
list. The find() method returns the first matching
element, or undefined if no match exists.
function findUserById(id) {
const users = readUsers();
const user = users.find(user => user.id === id);
if (user) {
console.log("User found:", user);
} else {
console.log("User not found.");
}
}
Calling the Function
findUserById(1);
findUserById(99);
Example output:
User found: {
id: 1,
name: 'Samadhan',
email: 'samadhan@example.com',
city: 'Pune'
}
User not found.
10. UPDATE — Modify User Information
The Update operation finds the required user, changes a property, and saves the modified array to the file.
function updateUserCity(id, newCity) {
const users = readUsers();
const user = users.find(user => user.id === id);
if (!user) {
console.log("User not found.");
return;
}
user.city = newCity;
writeUsers(users);
console.log("User updated successfully:", user);
}
Calling the Function
updateUserCity(2, "Pune");
Before the update:
{
"id": 2,
"name": "Pradnya",
"email": "pradnya@example.com",
"city": "Mumbai"
}
After the update:
{
"id": 2,
"name": "Pradnya",
"email": "pradnya@example.com",
"city": "Pune"
}
The city changes from Mumbai to Pune. The updated data is then
written to users.json.
11. DELETE — Remove a User
The Delete operation removes a record from the array. The
filter() method creates a new array containing
all records except the selected user's ID.
function deleteUser(id) {
const users = readUsers();
const updatedUsers = users.filter(
user => user.id !== id
);
if (updatedUsers.length === users.length) {
console.log("User not found.");
return;
}
writeUsers(updatedUsers);
console.log("User deleted successfully.");
}
Calling the Function
deleteUser(1);
Example output:
User deleted successfully.
12. Complete Working Application
Now combine the functions into a single app.js file.
This complete version initializes the JSON file if it does not
exist and checks that its contents are a valid array before
performing operations.
const fs = require("fs");
const path = require("path");
const filePath = path.join(__dirname, "users.json");
// Create the file if it does not exist
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, "[]", "utf8");
}
// Read user records
function readUsers() {
const data = fs.readFileSync(filePath, "utf8");
const users = JSON.parse(data);
if (!Array.isArray(users)) {
throw new Error("users.json must contain a JSON array.");
}
return users;
}
// Write user records
function writeUsers(users) {
fs.writeFileSync(
filePath,
JSON.stringify(users, null, 2),
"utf8"
);
}
// Create
function addUser(name, email, city) {
const users = readUsers();
const emailExists = users.some(
user => user.email.toLowerCase() === email.toLowerCase()
);
if (emailExists) {
console.log("Email already exists.");
return;
}
const newId = users.length > 0
? Math.max(...users.map(user => user.id)) + 1
: 1;
const newUser = {
id: newId,
name,
email,
city
};
users.push(newUser);
writeUsers(users);
console.log("User added successfully.");
}
// Read
function getAllUsers() {
console.log(readUsers());
}
// Search
function findUserById(id) {
const user = readUsers().find(user => user.id === id);
console.log(user ?? "User not found.");
}
// Update
function updateUserCity(id, city) {
const users = readUsers();
const user = users.find(user => user.id === id);
if (!user) {
console.log("User not found.");
return;
}
user.city = city;
writeUsers(users);
console.log("User updated successfully.");
}
// Delete
function deleteUser(id) {
const users = readUsers();
const updatedUsers = users.filter(user => user.id !== id);
if (updatedUsers.length === users.length) {
console.log("User not found.");
return;
}
writeUsers(updatedUsers);
console.log("User deleted successfully.");
}
// Run the demonstration
try {
addUser("Samadhan", "samadhan@example.com", "Pune");
addUser("Pradnya", "pradnya@example.com", "Mumbai");
console.log("\\nAll users:");
getAllUsers();
console.log("\\nSearch user with ID 1:");
findUserById(1);
console.log("\\nUpdate user with ID 2:");
updateUserCity(2, "Pune");
console.log("\\nDelete user with ID 1:");
deleteUser(1);
console.log("\\nFinal users:");
getAllUsers();
} catch (error) {
console.error("Application error:", error.message);
}
13. Run the Application
Open the terminal in the project folder and run:
node app.js
On the first run, the program adds two users, displays them, searches for ID 1, updates ID 2, and deletes ID 1.
User added successfully.
User added successfully.
All users:
[
{
id: 1,
name: 'Samadhan',
email: 'samadhan@example.com',
city: 'Pune'
},
{
id: 2,
name: 'Pradnya',
email: 'pradnya@example.com',
city: 'Mumbai'
}
]
Search user with ID 1:
{
id: 1,
name: 'Samadhan',
email: 'samadhan@example.com',
city: 'Pune'
}
Update user with ID 2:
User updated successfully.
Delete user with ID 1:
User deleted successfully.
Final users:
[
{
id: 2,
name: 'Pradnya',
email: 'pradnya@example.com',
city: 'Pune'
}
]
The exact object formatting depends on the Node.js console. The final data should contain Pradnya's record, with the city set to Pune.
14. Common Errors and Solutions
| Error | Possible reason | Solution |
|---|---|---|
| ENOENT | The JSON file does not exist. | Create the file or initialize it in the program. |
| SyntaxError | The JSON text is invalid. | Check commas, quotes, brackets, and braces. |
| User not found | The requested ID does not exist. | Check the ID in the file. |
| Permission error | The application cannot access the file. | Check folder and file permissions. |
| Duplicate email | A user already has the email address. | Use a different email or update the existing record. |
15. Practice Exercises
- Add a user: Create a function that accepts name, email, and city.
-
Display users by city:
Use
filter()to display only users from Pune. -
Search by email:
Use
find()to locate a user by email. - Update email: Create a function to change an existing user's email.
- Count users: Display the total number of records in the JSON file.
- Handle invalid JSON: Test the program with malformed JSON and display a helpful error.
Summary
- A JSON file can store structured user records.
- The
fsmodule reads and writes file data. - The
pathmodule helps create file paths. JSON.parse()converts JSON text into JavaScript data.JSON.stringify()converts JavaScript data into JSON text.push()adds a record to an array.find()locates a matching record.filter()creates an array without the selected record.- CRUD stands for Create, Read, Update, and Delete.
- File-based storage is useful for learning, while production applications generally need stronger data management.