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 Setup

Learn how to prepare your computer for Node.js development, configure your project folder, understand environment variables, create JavaScript files, and execute your first Node.js application.

1. What Is a Node.js Development Environment?

A development environment is a collection of software tools, folders, and configurations required to create, test, and run an application.

For Node.js development, we need a working Node.js installation, npm, a code editor, and a terminal. These tools allow us to write JavaScript programs and execute them without opening a browser.

For example, when we create a file named app.js, Node.js can execute that file using the node command.

Important Concept: Installing Node.js and configuring a project are two different activities. First, we prepare the system. Then, we create a project and execute our application.

Tools Required for Node.js Development

Tool Purpose Example
Node.js Executes JavaScript outside the browser. Running app.js
npm Manages packages and project dependencies. npm install
Code Editor Creates and edits source code. Visual Studio Code
Terminal Executes commands and starts applications. PowerShell or Command Prompt
Project Folder Organizes application files. MyNodeApp

2. Node.js Environment Setup Workflow

Follow these steps in sequence to create a working Node.js development environment.

Step 1
Install Node.js
↓
Step 2
Verify Node.js and npm
↓
Step 3
Configure the system PATH if required
↓
Step 4
Create a project folder
↓
Step 5
Create JavaScript and package files
↓
Step 6
Execute and test the application

This workflow separates system configuration from application development. Once the environment works correctly, we can reuse it for multiple Node.js projects.

3. Verify Node.js and npm Installation

Before creating a project, check whether Node.js and npm are available in your terminal.

Step 1: Open the Terminal

On Windows, you can use any of the following:

  • Command Prompt
  • Windows PowerShell
  • Terminal inside your code editor

Step 2: Check the Node.js Version

Terminal Command
node --version

The node command starts the Node.js runtime. The --version option displays the installed version instead of executing an application.

Example Output
v22.x.x

The displayed version depends on the Node.js version installed on your computer.

Step 3: Check the npm Version

Terminal Command
npm --version

npm is the package manager commonly used with Node.js. It helps us install libraries, manage dependencies, and run project scripts.

Example Output
10.x.x
Remember: The Node.js and npm version numbers do not have to be identical. They represent two different tools. Their actual versions depend on your installation.

4. Understanding the System PATH

PATH is an operating system environment variable containing a list of directories where the system searches for executable commands.

When you type node in a terminal, the operating system searches the configured locations to find the Node.js executable. If the required directory is not available in PATH, the command might not be recognized.

How PATH Works

User types node --version
↓
Operating system searches PATH directories
↓
Executable Found

Node.js runs and displays its version.

Executable Not Found

The terminal reports that the command is not recognized.

Check the Node.js Command Location

On Windows Command Prompt, use:

Command Prompt
where node
where npm

These commands display the executable locations that Windows can find. If the commands return valid paths, the tools are discoverable through the current command environment.

If Node.js Is Not Recognized

  1. Confirm that Node.js is installed.
  2. Close and reopen the terminal.
  3. Check the installation directory and system PATH configuration.
  4. If PATH needs correction, add the correct Node.js installation directory.
  5. Open a new terminal and repeat the version commands.
Warning: Do not replace the entire PATH variable while troubleshooting. Preserve the existing entries and modify only what is necessary.

5. Create a Node.js Project Folder

A project folder keeps all files related to an application in one location. For this practical example, we will create a folder named NodeEnvironmentDemo.

Step 1: Create the Folder

Terminal
mkdir NodeEnvironmentDemo

The mkdir command creates a new directory. If the command succeeds, the folder is created in the current working directory.

Step 2: Move into the Folder

Terminal
cd NodeEnvironmentDemo

The cd command changes the current working directory. Subsequent commands will operate from this project folder unless you move somewhere else.

Step 3: Confirm the Current Directory

Windows Terminal
cd
Example Output
C:\Projects\NodeEnvironmentDemo

This is an illustrative path. Your actual project location may be different.

Practical Tip: Make sure your terminal is inside the correct project folder before creating files or initializing npm.

6. Create Your First Node.js Application

Now we will create a JavaScript file and execute it using Node.js. You can create the file using your code editor.

Step 1: Create app.js

Create a file named app.js inside the NodeEnvironmentDemo folder.

app.js
console.log("Welcome to Node.js!");
console.log("My development environment is ready.");
console.log("JavaScript is running outside the browser.");

Step 2: Understand the Code

Code Explanation
console.log() Prints a message to the console.
"Welcome to Node.js!" A string value passed to the function.
Separate statements Each statement prints its own message.

Step 3: Execute the Application

Run this command from the directory containing app.js.

Terminal
node app.js

Expected Output

Welcome to Node.js!
My development environment is ready.
JavaScript is running outside the browser.

Node.js reads the JavaScript file and executes its statements. The messages appear in the terminal, not on a browser webpage.

Key Difference: In a browser, JavaScript can interact with webpage elements. In Node.js, JavaScript runs in the Node.js runtime and can use Node.js APIs for tasks such as working with files and creating servers.

7. Initialize the Project Using npm

A JavaScript file can run without a package.json file. However, as a project grows, we need a standard place to store project information, scripts, and dependency details.

npm provides the npm init command to create the project's package configuration file.

Step 1: Initialize npm

Terminal
npm init -y

The init command initializes the project, and -y accepts the default answers to the initialization questions.

Step 2: Understand package.json

After successful initialization, npm creates a package.json file in the current directory. A simplified example is shown below.

package.json - Illustrative Example
{
  "name": "nodeenvironmentdemo",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
Property Meaning
name The package or project name.
version The project's version number.
main A package entry-point field; it does not automatically execute the file.
scripts Contains named commands that npm can execute.
dependencies Lists packages required by the application when dependencies are installed.
Note: The actual values generated by npm init -y can vary with your npm version and project details. The example above illustrates the structure.

8. Run the Application Using an npm Script

npm scripts let us define reusable commands in package.json. Instead of typing the full Node.js command every time, we can define a script named start.

Step 1: Update package.json

Add a start entry to the existing scripts object. Keep the rest of the file intact.

package.json - Scripts Section
"scripts": {
  "start": "node app.js"
}

Step 2: Execute the Script

Terminal
npm start

Expected Output

Welcome to Node.js!
My development environment is ready.
JavaScript is running outside the browser.

npm runs the configured start script, which executes node app.js. The JavaScript program produces the same messages as before.

9. Understand the Final Project Structure

After completing the practical steps, your project folder should contain the following files:

Project Structure
NodeEnvironmentDemo/
|
|-- app.js
|
|-- package.json
app.js

Contains the JavaScript application code that Node.js executes.

package.json

Contains project metadata and npm scripts, and can describe the application's dependencies.

Additional files and folders, such as package-lock.json and node_modules, may appear when packages are installed. They are not required for the basic example in this tutorial.

10. Common Environment Setup Errors

The following table explains common errors, their possible causes, and practical ways to resolve them.

Error Possible Cause Solution
Node.js command not recognized Node.js is not installed correctly or PATH is not configured. Check the installation and PATH, then open a new terminal.
npm command not recognized npm is unavailable in the current environment. Verify the installation and run npm --version.
Cannot find module or file The file is missing or the command uses the wrong path. Check the current directory and confirm the filename.
Cannot find package.json The current directory does not contain the project configuration. Move into the project folder and run npm init -y if needed.
Unexpected token or syntax error The JavaScript code contains invalid syntax. Check brackets, quotation marks, commas, and spelling.
Address or port already in use Another process is using the port required by a server. Check the running process or configure a different available port.
Debugging Tip: Read the complete error message. It often identifies the file, line number, missing command, or resource responsible for the problem.

11. CIIT Training Institute - Practical Task

Task: Configure and Run a Student Application

Create a new Node.js project and complete the following activities independently.

  1. Check the Node.js version.
  2. Check the npm version.
  3. Create a folder named StudentDemo.
  4. Move into the newly created folder.
  5. Create a JavaScript file named student.js.
  6. Print a course name and a welcome message using console.log().
  7. Run the file using node student.js.
  8. Initialize the project using npm init -y.
  9. Add a start script to execute student.js.
  10. Run the application using npm start.
Expected Result
Welcome to the Student Application!
Node.js environment is configured successfully.

Your application should run from the terminal, and the project should contain both the JavaScript file and package.json.

12. Summary

What We Learned

  • A Node.js development environment contains the tools needed to develop applications.
  • Node.js executes JavaScript outside the browser.
  • npm manages project packages, dependencies, and scripts.
  • The system PATH helps the terminal locate executable commands.
  • The mkdir command creates a directory.
  • The cd command changes the current directory.
  • The node app.js command executes a JavaScript file.
  • The npm init -y command initializes a project configuration.
  • npm scripts provide convenient commands for running applications.
  • Reading error messages helps identify environment and code problems.