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 Introduction in Node.js

Learn what JSON is, why it is used, how JSON represents data, and how Node.js applications work with JSON objects and files. Understand JSON syntax, data types, practical examples, and the difference between JavaScript objects and JSON strings.

1. What Is JSON?

JSON stands for JavaScript Object Notation. It is a text-based data format used to store and exchange structured data between applications.

JSON represents information using key-value pairs and arrays. It is commonly used when applications send data to a server, receive data from an API, or store structured information in a text file.

For example, a student record can contain a student's name, course, and marks. JSON provides a structured way to represent this information.

Example: Student Data in JSON

JSON
{
    "name": "Samadhan",
    "course": "Node.js",
    "marks": 85
}

In this example, name, course, and marks are keys. Their corresponding values are "Samadhan", "Node.js", and 85.

Definition: JSON is a lightweight text-based format for representing and exchanging structured data.

2. Why Do We Use JSON?

Applications often need to exchange information in a format that is easy to read and process. JSON is useful because it represents structured data in a compact text format.

  • Data Exchange: Applications can send and receive structured information.
  • API Communication: Web APIs commonly use JSON request and response bodies.
  • Data Storage: JSON can store structured information in text files.
  • Readable Structure: Keys and values make data easier to understand.
  • Nested Data: Objects and arrays can represent related information.
  • Language Support: Many programming languages can read and generate JSON.

3. How JSON Works in an Application

An application can convert structured data into a JSON string before sending or storing it. Another part of the application can parse that JSON string back into a usable data structure.

Step 1: Application Data

Example: a JavaScript object containing student details.

↓
Step 2: Convert to JSON

Use JSON.stringify() to create a JSON string.

↓
Step 3: Send or Store

Transfer the JSON text or save it in a file.

↓
Step 4: Parse JSON

Use JSON.parse() to convert valid JSON text into a JavaScript value.

4. JSON Syntax Rules

JSON follows specific syntax rules. A JSON document must follow these rules to be parsed successfully.

  • JSON object keys must be enclosed in double quotation marks.
  • String values must use double quotation marks.
  • Key-value pairs are separated using a colon (:).
  • Multiple properties are separated using commas.
  • Objects use curly braces { }.
  • Arrays use square brackets [ ].
  • JSON supports strings, numbers, booleans, null, objects, and arrays.
  • JSON does not support comments or trailing commas.

Valid JSON Example

JSON
{
    "name": "Pradnya",
    "age": 22,
    "isStudent": true,
    "city": "Pune"
}

Invalid JSON Example

Invalid JSON
{
    name: 'Pradnya',
    age: 22,
}

The invalid example uses an unquoted key, single quotes for a string, and a trailing comma. These do not follow JSON syntax.

Important: JavaScript object literals and JSON are not exactly the same. JavaScript allows some syntax that JSON does not, such as unquoted property names and single-quoted string literals.

5. JSON Data Types

JSON supports several data types. Choosing the correct type helps represent information accurately.

Data Type Example Description
String "name": "Samadhan" Represents text enclosed in double quotes.
Number "marks": 85 Represents an integer or decimal number.
Boolean "isActive": true Represents either true or false.
Null "middleName": null Represents an intentionally empty value.
Object "address": { "city": "Pune" } Represents a collection of key-value pairs.
Array "skills": ["JavaScript", "Node.js"] Represents an ordered collection of values.

Complete JSON Example

JSON
{
    "name": "Samadhan",
    "age": 22,
    "marks": 85.5,
    "isStudent": true,
    "middleName": null,
    "address": {
        "city": "Pune",
        "state": "Maharashtra"
    },
    "skills": [
        "JavaScript",
        "Node.js",
        "SQL"
    ]
}

This example combines strings, numbers, a boolean, null, a nested object, and an array in one JSON document.

6. JSON vs JavaScript Object

JSON and JavaScript objects look similar, but they serve different purposes. A JavaScript object is a runtime value that a program can work with directly. JSON is a text format used to represent data.

JavaScript Object

JavaScript
const student = {
    name: "Samadhan",
    marks: 85
};

console.log(student.name);

Output

Output
Samadhan

Equivalent JSON Text

JSON
{
    "name": "Samadhan",
    "marks": 85
}

Notice that JSON requires double quotes around property names and string values. A JavaScript object can be used directly by JavaScript code, while JSON text must be parsed before accessing its data as an object.

7. Using JSON in Node.js

Node.js includes the global JSON object. Its two commonly used methods are JSON.stringify() and JSON.parse().

  • JSON.stringify(): Converts a JavaScript value into a JSON string.
  • JSON.parse(): Parses valid JSON text and returns the corresponding JavaScript value.
Remember: You do not need to install a separate package to use JSON.stringify() or JSON.parse(). They are available through JavaScript's built-in JSON object.

8. Practical Program: Create and Display JSON Data

Let us create a JavaScript object containing student details and display its properties in the terminal.

Complete Program

JavaScript - app.js
const student = {
    name: "Samadhan",
    course: "Node.js",
    marks: 85
};

console.log("Student Name:", student.name);
console.log("Course:", student.course);
console.log("Marks:", student.marks);

Output

Output
Student Name: Samadhan
Course: Node.js
Marks: 85

Explanation: The student variable stores a JavaScript object. Dot notation accesses individual properties such as student.name and student.marks.

9. JSON Conversion Flow

The following diagram explains the conversion between JavaScript values and JSON text.

JavaScript Object

{ name: "Samadhan", marks: 85 }

↓
JSON.stringify()

Converts the object into JSON text.

↓
JSON String

{"name":"Samadhan","marks":85}

↓
JSON.parse()

Converts valid JSON text back into a JavaScript value.

10. How to Run the Program

  1. Create a folder named JSONExample.
  2. Create a JavaScript file named app.js.
  3. Write the student object program in that file.
  4. Open a terminal in the project folder.
  5. Run the file using the Node.js command.

Terminal Command

Terminal
node app.js

Node.js executes the JavaScript file and prints the student details in the terminal.

11. Common JSON Mistakes

Mistake Correct Approach
Using single quotes for JSON strings. Use double quotes for JSON string values.
Leaving object property names unquoted. Enclose JSON property names in double quotes.
Adding a trailing comma. Remove the comma after the final property or array element.
Using comments inside JSON. Keep comments outside the JSON document.
Parsing invalid JSON text. Ensure the text follows JSON syntax before parsing.
Confusing a JavaScript object with a JSON string. Use JSON.stringify() and JSON.parse() when conversion is needed.

12. Practice Tasks

Task 1: Create Employee JSON Data

Create a JavaScript object containing employee ID, name, department, and salary. Display each property in the terminal.

Task 2: Create Product JSON Data

Create a product object with product name, price, availability, and category. Use appropriate data types for each property.

Task 3: Work with Nested JSON Data

Create a student object containing a nested address object and an array of skills. Display the student's city and the first skill in the terminal.

Important Points

  • JSON stands for JavaScript Object Notation.
  • JSON is a text format used to represent structured data.
  • JSON keys and string values require double quotes.
  • JSON supports strings, numbers, booleans, null, objects, and arrays.
  • JSON does not support comments or trailing commas.
  • JSON.stringify() converts a JavaScript value into a JSON string.
  • JSON.parse() parses valid JSON text into a JavaScript value.
  • JSON is commonly used for API communication and structured data storage.

Summary

JSON stands for JavaScript Object Notation and is a text-based format used to represent and exchange structured data. It supports strings, numbers, booleans, null, objects, and arrays. JSON follows strict syntax rules, including double-quoted property names and string values, and does not allow comments or trailing commas. In Node.js, JSON.stringify() converts JavaScript values into JSON text, while JSON.parse() converts valid JSON text back into JavaScript values. JSON is widely used for API communication, data exchange, and structured storage.