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

Node.js Environment Variables

Environment variables allow Node.js applications to read configuration values from their execution environment. They help us configure applications without changing the source code.

1. What Are Environment Variables?

Environment variables are named values provided to an application by its operating system, terminal, deployment environment, or configuration setup.

For example, a Node.js application may need an application name, server port, or environment name. Instead of hardcoding these values, we can read them from environment variables.

Common examples of environment variables are:

  • APP_NAME — application name.
  • PORT — server port number.
  • NODE_ENV — application environment.
  • DB_HOST — database server configuration.
Remember: Environment variables separate application configuration from source code. Passwords and other sensitive values must also be protected from unauthorized access.

2. Understanding process.env

Node.js provides the process.env object to access environment variables available to the running process.

We can read a particular variable by using its name as a property of process.env.

Example

JavaScript
console.log(process.env.APP_NAME);
console.log(process.env.PORT);
console.log(process.env.NODE_ENV);

Possible Output

Output
CIITApp
5000
development

Explanation: These values appear when the corresponding environment variables have been configured. If a variable is missing, its value may be undefined.

Important: Environment variable values are generally strings. Convert and validate them when your application expects a number or another specific data type.

3. Environment Variables Workflow Diagram

This diagram shows how environment variables are supplied to a Node.js application and accessed through process.env.

Operating System / Terminal

Provides configuration values

↓
Environment Variables

APP_NAME, PORT, NODE_ENV

↓
Node.js process.env

Reads the configured values

↓
Node.js Application

Uses configuration to perform its work

Note: This is a simplified learning diagram showing the basic flow of configuration values.

4. How to Set Environment Variables

Environment variables can be set in the terminal before running a Node.js program. The command depends on the terminal being used.

Windows Command Prompt (CMD)

CMD
set APP_NAME=CIITApp
set PORT=5000
node app.js

Windows PowerShell

PowerShell
$env:APP_NAME = "CIITApp"
$env:PORT = "5000"
node app.js

Linux / macOS Terminal

Terminal
APP_NAME=CIITApp PORT=5000 node app.js

Explanation: These commands configure environment variables for the Node.js process. In CMD and PowerShell, the variables also remain available in the current terminal session until changed or the session ends.

5. Practical Program Using Environment Variables

Let us create a program that reads the application name, environment name, and port number from environment variables.

Step 1: Create a File

Create a file named app.js.

Step 2: Write the Program

JavaScript
const appName = process.env.APP_NAME || "DefaultApp";
const environment = process.env.NODE_ENV || "development";
const port = process.env.PORT || "3000";

console.log("Application Name:", appName);
console.log("Environment:", environment);
console.log("Port:", port);

Step 3: Run the Program

In Windows Command Prompt, execute:

CMD
set APP_NAME=CIITApp
set NODE_ENV=development
set PORT=5000
node app.js

Step 4: Expected Output

Output
Application Name: CIITApp
Environment: development
Port: 5000

Step 5: Understand the Program

  • process.env.APP_NAME reads the application name.
  • process.env.NODE_ENV reads the environment name.
  • process.env.PORT reads the configured port.
  • The || operator provides a fallback when the environment variable value is falsy.

6. Using a .env File

A .env file stores configuration values in key-value format. It is commonly used during local development.

Example .env File

.env
APP_NAME=CIITApp
NODE_ENV=development
PORT=5000

In Node.js versions that support the built-in --env-file option, the file can be loaded while starting the application.

Run the Program

Terminal
node --env-file=.env app.js

After the file is loaded, the application can read its values using process.env.

Security Tip: Do not commit real passwords, API keys, or database credentials to source control. Keep local .env files out of version control and protect sensitive production configuration.

7. Validating an Environment Variable

Because environment variable values are generally strings, we should validate values before using them in important operations. The following example checks whether a port is a valid integer.

JavaScript
const rawPort = process.env.PORT ?? "3000";
const port = Number(rawPort);

if (
    !Number.isInteger(port) ||
    port < 1 ||
    port > 65535
) {
    throw new Error("PORT must be a valid port number.");
}

console.log("Validated Port:", port);

Expected Output

Output
Validated Port: 5000

Explanation: If PORT is set to 5000, the program converts the value to a number and validates its range. If the value is invalid, the program throws an error.

8. Common Mistakes

Mistake Reason Solution
Variable is undefined The variable has not been set or loaded. Check the terminal command or configuration file.
Using a string as a number Environment values are generally strings. Convert and validate the value.
Incorrect variable name The configured name does not match the code. Use consistent variable names.
Exposing sensitive values Credentials are stored in committed source code. Use secure configuration and secret management.
Old configuration values The running process still has previously loaded values. Restart the application after changing configuration.

9. Practice Task

Application Configuration Program

Create a Node.js program that reads configuration values from environment variables.

Requirements:

  • Read the application name from APP_NAME.
  • Read the environment from NODE_ENV.
  • Read the port number from PORT.
  • Display all three values in the terminal.
  • Provide suitable defaults for optional values.
  • Validate the port before using it.
Challenge: Display an error message when the port is not an integer or is outside the valid range of 1 to 65535.

Important Points

  • process.env is used to access environment variables.
  • Environment variable values are generally strings.
  • Terminal commands can set variables before running a program.
  • A .env file can organize local configuration.
  • Validate configuration values before using them.
  • Never expose real passwords or API keys in source control.

Summary

Environment variables provide configuration values to Node.js applications. The process.env object allows us to access these values. We can set variables through the terminal or load them from a supported .env file. Values should be validated before use, and sensitive configuration must be protected from unauthorized access.