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

NPM Setup

npm is an essential tool in Node.js development. It helps developers install reusable packages, manage project dependencies, and execute application scripts.

In this lesson, we will learn how npm works, verify its installation, initialize a Node.js project, understand package.json, install a package, and execute a JavaScript program using npm.

1. Learning Objectives

After completing this lesson, you will be able to:

  • Understand npm and its role in Node.js development.
  • Verify the installed npm version.
  • Initialize a project using npm.
  • Understand package.json and package-lock.json.
  • Install, use, and remove npm packages.
  • Configure and execute npm scripts.

2. What Is npm?

npm stands for Node Package Manager. It is commonly used with Node.js to install and manage reusable JavaScript packages.

A package contains code that developers can reuse instead of implementing every feature from scratch. For example, a package may provide email validation, date formatting, logging, or other useful functionality.

Why Do We Use npm?

  • To install packages required by an application.
  • To manage project dependencies.
  • To record package versions.
  • To define reusable project commands.
  • To help developers reproduce the project's dependency setup.
Remember: Node.js provides the runtime for executing JavaScript. npm helps manage packages and scripts used in Node.js projects.

3. How npm Works

When we install a package, npm reads the project configuration, resolves the package dependencies, downloads the required package files, and updates the dependency information when appropriate.

Developer

Runs an npm command

↓
npm

Resolves packages and dependencies

↓
Package Registry

Provides package information and files

↓
Project Dependencies

Packages become available to the application

Package installation normally requires network access unless the required package data is already available locally or through an appropriately configured cache or registry.

4. Verify npm Installation

npm is generally installed along with Node.js when using the standard Node.js installer. We can verify it through the terminal.

Step 1: Open the Terminal

On Windows, open Command Prompt or PowerShell.

Step 2: Check the npm Version

Command Prompt
npm --version

Example Output

Output — example only
10.x.x

The exact version depends on the installed npm release. If the command displays a version number, npm is accessible from the current terminal.

Check the Node.js Version Too

Command Prompt
node --version
npm --version

Both commands should display version information when Node.js and npm are installed and available through the terminal.

5. Common npm Commands

npm provides commands for initializing projects, installing packages, removing dependencies, and running scripts.

Command Purpose
npm --version Displays the npm version.
npm init Starts the project initialization process.
npm init -y Creates package.json using default answers.
npm install Installs the project's declared dependencies.
npm install package-name Installs a specified package.
npm uninstall package-name Removes a package from the project.
npm run Lists the available package scripts.

6. Create a Node.js Project Using npm

Before installing packages, we should create a project folder and initialize it using npm.

Step 1: Create a Project Folder

Create a folder named NpmPractice. Open a terminal in that folder.

Step 2: Initialize the Project

Terminal
npm init -y

The -y option accepts the default answers to the initialization questions. npm creates a package.json file.

Step 3: Understand the Project Structure

Project Structure
NpmPractice/
└── package.json

At this stage, the project contains its package configuration. We can now add JavaScript files and install packages as required.

7. What Is package.json?

package.json is the main project configuration file used by npm. It contains information such as the project name, version, dependencies, and scripts.

Example package.json

JSON — package.json
{
  "name": "npm-practice",
  "version": "1.0.0",
  "description": "A beginner Node.js project",
  "main": "app.js",
  "scripts": {
    "start": "node app.js"
  }
}

Explanation of Properties

Property Explanation
name Defines the project name.
version Defines the project version.
description Provides a short project description.
main Specifies the package entry point in applicable package contexts.
scripts Defines commands that can be executed through npm.
Important: package.json must contain valid JSON. Use double quotes around property names and string values. Do not add comments or trailing commas to standard JSON.

8. Install an npm Package

npm allows us to add reusable functionality to our project. In this example, we will install the validator package, which provides validation functions.

Step 1: Install the Package

Terminal
npm install validator

npm downloads the package and its required dependencies. It also records the dependency information in package.json and updates package-lock.json when appropriate.

Step 2: Understand the Structure

Project Structure
NpmPractice/
├── node_modules/
├── package.json
├── package-lock.json
└── app.js
  • node_modules contains the installed package files.
  • package.json records project configuration and dependencies.
  • package-lock.json records the resolved dependency tree.
  • app.js contains the application's JavaScript code.

9. Use the Installed Package

After installing the package, create a file named app.js in the project folder.

JavaScript — app.js
const validator = require("validator");

const email = "student@example.com";

if (validator.isEmail(email)) {
    console.log("Valid email address");
} else {
    console.log("Invalid email address");
}

Run the Program

Terminal
node app.js

Expected Output

Output
Valid email address

Program Explanation

  • require("validator") imports the installed package using CommonJS syntax.
  • validator.isEmail(email) checks whether the supplied string has a valid email format.
  • The if statement checks the returned Boolean value.
  • console.log() displays the result in the terminal.
Note: Install the package before running this program. This example uses CommonJS syntax.

10. Run Scripts Using npm

npm scripts allow developers to define reusable commands inside the scripts section of package.json.

Example package.json

JSON — package.json
{
  "name": "npm-practice",
  "version": "1.0.0",
  "scripts": {
    "start": "node app.js",
    "check": "node --version"
  }
}

Execute the Start Script

Terminal
npm start

npm executes the command configured under the start script. In this example, it runs node app.js.

Execute the Check Script

Terminal
npm run check

This command runs node --version and displays the active Node.js runtime version.

11. Common npm Problems

Problem Possible Reason Solution
npm is not recognized npm is missing or unavailable in PATH. Verify the Node.js installation and reopen the terminal.
package.json not found The command is running in the wrong directory. Navigate to the project folder and check the file.
Cannot find module The package is missing or cannot be resolved. Check the package name and install the required dependency.
Network error Internet, proxy, or registry connectivity problems. Check the connection and npm configuration.
Invalid JSON Incorrect syntax in package.json. Check quotation marks, commas, and braces.

Important Points

  • Use npm --version to check npm.
  • Use npm init -y to initialize a basic project.
  • Use npm install package-name to install a package.
  • Use package.json to manage project configuration.
  • Use package-lock.json to record resolved dependency versions.
  • Use npm scripts to execute reusable commands.

Practical Learning at CIIT TRAINING INSTITUTE

At CIIT TRAINING INSTITUTE, learners can practise npm commands and understand how real Node.js projects manage packages. These skills prepare learners for the next stages of backend development, including Express.js, REST APIs, databases, and authentication.

Skills Covered in This Lesson
  • Verify npm installation.
  • Initialize a Node.js project.
  • Understand package.json and package-lock.json.
  • Install and use an npm package.
  • Configure and execute npm scripts.

Summary

npm helps developers install packages, manage dependencies, and execute project scripts. The package.json file stores project configuration, while package-lock.json records the resolved dependency tree. By practising npm commands and using packages in JavaScript programs, learners at CIIT TRAINING INSTITUTE can prepare for larger Node.js application development.