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

Installing Packages in Node.js

NPM allows developers to install reusable packages in Node.js applications. Packages provide ready-made functionality that helps developers build applications without writing every feature from scratch.

In this tutorial, we will learn how to install packages locally, understand the node_modules folder, use installed packages in JavaScript, remove packages, and manage package installations through NPM commands.

Learning objective: Learn how to install, use, inspect, and uninstall NPM packages in a Node.js project.

1. What Is an NPM Package?

An NPM package is a collection of reusable JavaScript code and related files. A package may provide functionality for creating web servers, validating input, handling dates, testing code, or performing other common tasks.

For example, Express is a package commonly used to build web servers and REST APIs with Node.js.

Node.js Project

Your application code

↓
NPM

Downloads and manages packages

↓
Installed Packages

Reusable functionality for your project

2. Create a Node.js Project

Before installing a package, create a project folder and initialize it with NPM.

Step 1: Create a folder

Terminal
mkdir PackageDemo
cd PackageDemo

The mkdir command creates a directory, and cd moves the terminal into that directory.

Step 2: Initialize NPM

Terminal
npm init -y

This command creates a default package.json file that stores project information and dependency details.

Project structure

PackageDemo/
|
|-- package.json

3. Install a Package Using npm install

The npm install command installs a package into your project.

Syntax

Terminal
npm install package-name

Example: Install Express

Terminal
npm install express

This command generally performs the following tasks:

  • Downloads Express and its required dependencies.
  • Creates or updates the node_modules folder.
  • Records Express in package.json.
  • Updates package-lock.json to record resolved versions.

After installation, the project structure may look like this:

PackageDemo/
|
|-- node_modules/
|   |-- express/
|   |-- ...
|
|-- package.json
|
|-- package-lock.json
Remember: The exact contents of node_modules depend on the installed package versions and their dependencies.

4. Understand node_modules

The node_modules folder stores the packages installed for the project, including their dependencies. Node.js can resolve packages from this folder when application code imports or requires them.

File or Folder Purpose
node_modules Contains installed package files.
package.json Defines project metadata and declared dependencies.
package-lock.json Records the resolved dependency tree and versions.
app.js Contains the application's JavaScript code.

Usually, developers do not manually edit files inside node_modules. NPM manages the installed package files.

5. Use an Installed Package

After installing a package, we can use its exported functionality in our JavaScript application.

Step 1: Install Express

Terminal
npm install express

Step 2: Create app.js

JavaScript
const express = require("express");

const app = express();

app.get("/", (req, res) => {
    res.send("Welcome to my Node.js application!");
});

app.listen(3000, () => {
    console.log("Server running on port 3000");
});

Understanding the Code

  • require("express") loads the installed Express package.
  • express() creates an application instance.
  • app.get() defines a handler for GET requests to the root path.
  • res.send() sends a response to the client.
  • app.listen() starts the server on port 3000.

Step 3: Run the application

Terminal
node app.js

Expected terminal output:

Output
Server running on port 3000

When you send a GET request to the root path on the local server, the response body will be:

Response
Welcome to my Node.js application!
The server keeps running until you stop the process. Press Ctrl + C in the terminal to stop it. The port must also be available for the application to start successfully.

6. Install a Development Package

Some packages are primarily used during development rather than by the deployed application. Nodemon is a tool that can restart a Node.js application when watched files change.

Install Nodemon

Terminal
npm install nodemon --save-dev

The --save-dev option records Nodemon under devDependencies in package.json.

Example package.json

JSON
{
  "devDependencies": {
    "nodemon": "^3.0.0"
  }
}

This is an illustrative version range. The version recorded by NPM may be different.

Run Nodemon

Terminal
npx nodemon app.js

Nodemon watches the relevant files and restarts the application when changes are detected. It is useful during development.

7. Install a Specific Package Version

Sometimes a project requires a particular package version. NPM lets us request a specific version during installation.

Syntax

Terminal
npm install package-name@version

Example

Terminal
npm install express@4

This requests a compatible Express 4.x version. The exact version installed depends on NPM's version resolution and the project's existing constraints.

The installed version is recorded in the dependency information. Check the result with:

Terminal
npm list express

8. Uninstall a Package

If a package is no longer required, remove it from the project using the npm uninstall command.

Syntax

Terminal
npm uninstall package-name

Example

Terminal
npm uninstall express

When successful, NPM generally:

  • Removes the package from the project's installed dependencies.
  • Updates the dependency declaration in package.json.
  • Updates package-lock.json.
If your application imports Express, it will no longer run successfully after Express has been uninstalled unless you install it again or change the code.

9. Useful NPM Installation Commands

Command Purpose
npm install Installs project dependencies from the manifest and lockfile when available.
npm install express Installs Express as a dependency.
npm install nodemon --save-dev Installs Nodemon as a development dependency.
npm install express@4 Requests a compatible Express 4.x version.
npm uninstall express Removes Express from the project.
npm list Displays the installed dependency tree.
npm list --depth=0 Displays top-level installed packages.
npx nodemon app.js Runs Nodemon for the application.

10. Common Package Installation Errors

Problem Possible Cause Solution
npm is not recognized Node.js or NPM may not be installed correctly or may not be on PATH. Verify the installation and reopen the terminal.
Cannot find module The required package is missing or cannot be resolved. Install the package in the correct project directory.
Network error Network, proxy, or registry connectivity issue. Check the connection and NPM registry configuration.
Permission denied The current account cannot access a required location. Check permissions and the installation location.
Port already in use Another process is using the application's port. Stop the other process or configure another port.

11. Practice Tasks

  1. Create a project named EmployeeApp.
  2. Initialize it using npm init -y.
  3. Install Express in the project.
  4. Create an Express server on port 3000.
  5. Return a welcome message from the root route.
  6. Install Nodemon as a development dependency.
  7. Display installed top-level packages.
  8. Uninstall a package and observe the changes in package.json.

Summary

NPM helps developers install, manage, and remove reusable packages in Node.js applications. The npm install command adds packages to a project, while npm uninstall removes packages that are no longer required. Installed packages are stored in the node_modules folder, and package.json and package-lock.json record dependency information. Development packages such as Nodemon can help improve the development workflow. Understanding package installation is an important step toward building and maintaining practical Node.js applications at CIIT TRAINING INSTITUTE.