Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

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.

Learning objective: By the end of this lesson, you will understand how to store user records in a JSON file and perform Create, Read, Update, and Delete operations using Node.js.

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

users.json
[
  {
    "id": 1,
    "name": "Samadhan",
    "email": "samadhan@example.com",
    "city": "Pune"
  },
  {
    "id": 2,
    "name": "Pradnya",
    "email": "pradnya@example.com",
    "city": "Mumbai"
  }
]

In this example:

  • id uniquely identifies a record in this example.
  • name stores the user's name.
  • email stores the user's email address.
  • city stores the user's city.
Remember: A JSON file is simple file-based storage. It is useful for learning and small demonstrations, but it is not a full database such as SQL Server or MongoDB.

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.

Step 1: Node.js Application

User requests an operation

↓
Step 2: Read the JSON File

Use the fs module

↓
Step 3: Convert JSON Text

JSON.parse() creates JavaScript data

↓
Step 4: Perform the Operation

Add, search, update, or delete a user

↓
Step 5: Save Updated Data

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.

users.json
[]

Step 2: Import the Modules

JavaScript
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:

JavaScript
const filePath = path.join(__dirname, "users.json");
  • __dirname represents the directory containing the current script.
  • path.join() combines the directory and file name.
  • filePath stores 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.

JavaScript
function readUsers() {
    const data = fs.readFileSync(filePath, "utf8");
    const users = JSON.parse(data);

    return users;
}

Understanding the Code

  1. readFileSync() reads the file contents.
  2. "utf8" tells Node.js to return the content as text.
  3. JSON.parse(data) converts the JSON text into a JavaScript value.
  4. return users sends the resulting array back to the calling function.

Example

JavaScript
const users = readUsers();

console.log(users);

If the file contains an empty array, the output is:

Output
[]
Important: This simple version expects the file to exist and contain valid JSON. We will add error handling in a later section.

5. Save Data into the JSON File

After changing a user's information, we need to save the updated array back into the file.

JavaScript
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

JavaScript
const users = [
    {
        id: 1,
        name: "Samadhan",
        email: "samadhan@example.com",
        city: "Pune"
    }
];

writeUsers(users);

The file will contain:

users.json
[
  {
    "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.

JavaScript
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

JavaScript
addUser(
    "Samadhan",
    "samadhan@example.com",
    "Pune"
);

Example output:

Output
User added successfully: {
  id: 1,
  name: 'Samadhan',
  email: 'samadhan@example.com',
  city: 'Pune'
}
This ID calculation is suitable for a small demonstration, not a concurrent production database. Duplicate IDs or emails should also be checked if the application requires uniqueness.

8. READ — Display All Users

The Read operation retrieves all records from the file and displays them in the terminal.

JavaScript
function getAllUsers() {
    const users = readUsers();

    console.log("All Users:");
    console.log(users);
}

Calling the Function

JavaScript
getAllUsers();

Example output when two users exist:

Output
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.

JavaScript
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

JavaScript
findUserById(1);
findUserById(99);

Example output:

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.

JavaScript
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

JavaScript
updateUserCity(2, "Pune");

Before the update:

JSON
{
  "id": 2,
  "name": "Pradnya",
  "email": "pradnya@example.com",
  "city": "Mumbai"
}

After the update:

JSON
{
  "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.

JavaScript
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

JavaScript
deleteUser(1);

Example output:

Output
User deleted successfully.
Note: Deleting a user changes the JSON file itself. Keep a backup if you need to preserve the original records.

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.

app.js
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);
}
Important for repeated runs: The demo adds the same email addresses each time. The duplicate email check prevents adding them again, so the later operations can still update or delete existing records. If you manually corrupt the JSON file, the application reports an error rather than silently replacing the records.

13. Run the Application

Open the terminal in the project folder and run:

Terminal
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.

Expected Output — First Run
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.
Production tip: For important user data, use a proper database and suitable validation, authentication, access controls, and backups. A JSON file can be overwritten or corrupted, and synchronous file operations block the Node.js event loop while they run.

15. Practice Exercises

  1. Add a user: Create a function that accepts name, email, and city.
  2. Display users by city: Use filter() to display only users from Pune.
  3. Search by email: Use find() to locate a user by email.
  4. Update email: Create a function to change an existing user's email.
  5. Count users: Display the total number of records in the JSON file.
  6. Handle invalid JSON: Test the program with malformed JSON and display a helpful error.

Summary

  • A JSON file can store structured user records.
  • The fs module reads and writes file data.
  • The path module 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.