DEPARTMENT OF COMPUTER AND COMMUNICATION ENGINEERING
Subject Name: Internet and Web Programming
Subject Code: U23CCT601
Basics of Node JS-Instaliation-Working with Node packages - Using Node package manager-
Creating a simple COS [Link] application-Using Events-Listeners-Timers-Callbacks-
Handling Data I/O-Implementing HTTP services in [Link].
BASICS OF NODE JS
[Link] is [Link]?
[Link] is a free, open source tool that lets you run JavaScript outside the web browser.
With [Link], you can build fast and scalable applications like web servers, APIs, tools, and
more.
[Link] to print a message in [Link]?
[Link]('Hello from [Link]!');
3. Why [Link]?
[Link] excels at handling many simultaneous connections with minimal overhead, making it
perfect for:
Real-time applications (chats, gaming, collaboration tools)
APIs and microservices
Data streaming applications
Command-line tools
Server-side web applications
Its non-blocking, event-driven architecture makes it highly efficient for I/O-heavy workloads.
4. What Can [Link] Do?
Web Servers: Create fast, scalable network applications
File Operations: Read, write, and manage files on the server
Database Interaction: Work with databases like MongoDB, MySQL, and more
APIs: Build RESTful services and GraphQL APIs
Real-time: Handle WebSockets for live applications
CLI Tools: Create command-line applications
[Link] is the key difference between [Link] and Browser?
[Link] and browsers both run JavaScript, but they have different environments and
capabilities.
[Link] is designed for server-side development, while browsers are for client-side
applications.
APIs: [Link] provides APIs for file system, networking, and OS, which browsers do
not.
Browsers provide DOM, fetch, and UI APIs not available in [Link].
Global Objects: [Link] uses global; browsers use window or self.
Modules: [Link] uses CommonJS (require) and ES modules (import); browsers use
ES modules or plain <script> tags.
Security: Browsers run in a sandbox with limited access; [Link] has full access to
the file system and network.
Event Loop: Both environments use an event loop, but [Link] has additional APIs
for timers, process, etc.
Environment Variables: [Link] can access environment variables ([Link]);
browsers cannot.
Package Management: [Link] uses npm/yarn; browsers use CDNs or bundlers.
NODEJS BASICS:
NodeJS is a JavaScript runtime environment built on Chrome’s V8 JavaScript engine that
allows developers to execute JavaScript code outside the browser. It can make console-
based and web-based NodeJS applications.
Some of the features of the NodeJs are mentioned below:
Non-blocking I/O: NodeJS is asynchronous, enabling efficient handling of concurrent
requests.
Event-driven architecture: Developers can create event-driven applications using
callbacks and event emitters.
Extensive module ecosystem: NPM (Node Package Manager) provides access to
thousands of reusable packages.
Single-threaded Model: Node js runs on a single thread despite being asynchronous,
it uses an event loop to handle requests.
Setting Up Nodejs:
To start using NodeJS, you’ll first need to install it on your system.
Step 1: Download and Install NodeJS
Go to the NodeJS official website or you can follow our article to install NodeJS
Download the appropriate installer for your operating system (Windows, macOS, or
Linux).
Follow the installation steps to set up NodeJS.
Step 2: Verify Installation
Once installed, you can verify the installation by opening your terminal and typing the
following commands:
node -v
npm -v
Step 3: Create a NodeJS Project
Create a new directory for your project and initialize it with npm by running.
mkdir node-project
cd node-project
This will generate a [Link] file, which is essential for managing your project
dependencies.
npm init -y
Step 4: Write Your First NodeJS Application:
Create a new file called [Link] and add the following code to create a simple HTTP server:
const http = require('http');
const server = [Link]((req, res) => {
[Link]('Hello World!');
[Link]();
});
[Link](3000, () => {
[Link]('Server running on port 3000');
});
OUTPUT:
node [Link]
In this example
The http module is imported using require('http') to allow you to create an HTTP
server.
[Link] creates a new server that listens for incoming HTTP requests.
The callback function (req, res) handles requests and responses.
Inside the callback, [Link]('Hello, World!') sends "Hello, World!" as a response, and
[Link]() ends the response.
[Link](3000) starts the server on port 3000. Once the server is running, it logs
"Server running on port 3000" to the console.
Nodejs Architecture:
NodeJS follows a single-threaded event loop model that handles all client requests using a
single thread. It is based on a non-blocking I/O model, meaning the server can process
multiple requests without waiting for one task to complete before starting the next.
Event Loop: The event loop processes tasks without blocking, allowing NodeJS to
handle many requests concurrently on a single thread.
Asynchronous Execution: Non-blocking functions are used for tasks such as reading
from the file system or querying databases. This ensures the application remains
responsive.
Basic Nodejs Concepts:
1. Modules in NodeJS
NodeJS is built around the concept of modules. Modules in NodeJS are reusable pieces of
code that can be imported into your application. These can be built-in modules (like fs for
file system operations, http for HTTP server, etc.) or external packages installed using NPM.
Common NodeJS Modules
HTTP Module: The http module is used to create web servers. It allows you to handle
requests and send responses.
FS (File System) Module: The fs module provides an API to interact with the file
system. It can be used to read and write files, check for file existence, etc.
Path Module: The path module helps in handling and transforming file paths. It
makes working with file systems easier and more cross-platform.
Event Module: The events module allows objects to emit and listen to events, which
helps in writing event-driven applications.
Express Framework: While NodeJS provides basic capabilities, many developers use
the Express framework, which simplifies routing, middleware integration, and HTTP
request handling.
2. Event Loop and Asynchronous Programming:
NodeJS uses an event loop to handle asynchronous operations. Rather than waiting for tasks
(like I/O operations) to complete, NodeJS executes them in the background and moves on to
other tasks. Once a task is complete, the corresponding callback is invoked. This non-
blocking approach helps build highly responsive applications, especially useful for web
servers and real-time applications.
Advantages of Using NodeJS
High Performance: NodeJS is optimized for performance due to its non-blocking I/O
model and V8 engine, making it highly suitable for handling real-time applications
and large-scale systems.
Scalable: With its event-driven architecture, NodeJS can handle a large number of
concurrent connections, making it highly scalable.
Cross-Platform: NodeJS is cross-platform, meaning it can run on various operating
systems like Windows, macOS, and Linux.
Active Community: NodeJS has a large and active community that constantly
contributes to its growth. This results in a vast array of open-source libraries and
tools that can be easily integrated into your application.
INSTALLATION:
How to Download and Install [Link] and NPM
NodeJS and NPM (Node Package Manager) are essential tools for modern web development.
NodeJS is the runtime environment for JavaScript that allows you to run JavaScript outside
the browser, while NPM is the package manager that helps manage libraries and code
packages in your projects.
To run a [Link] project on your system, you first need to install [Link] and NPM. Once
installed, you can use the [Link] runtime to execute JavaScript code and NPM to manage
project dependencies and packages.
Note: We do not need to download NodeJS and NPM separately. When we install NodeJS,
NPM (Node Package Manager) is installed automatically along with it.
How to download and install NodeJS and NPM
Follow the below given steps below to download and install NodeJS and npm on your
system:
Step 1: Download the package from its Official Website
Go to the official NodeJS website.
You will see two main download options:
LTS (Long-Term Support): This version is recommended for most users, especially
for production environments, as it is stable and receives long-term updates.
Current: This version includes the latest features but may not be as stable as the LTS
version.
Click on the version you wish to download. The website will automatically detect
your operating system and recommend the appropriate version (Windows, macOS, or
Linux).
Official Website
Installing NodeJS is the first step towards building scalable web applications.
Step 2: Install NodeJS and NPM
Now you need to install the NodeJS installer on your system. You need to follow the
following steps for NodeJS to be installed.
Double-click on the .msi installer. The NodeJS Setup wizard will open.
Welcome To NodeJS Setup Wizard.
Now, select “Next” to proceed.
SetupWizard
Step 3: Finish Setting up
Go through the terms and license carefully before finishing up the setup.
After clicking “Next”, the End-User License Agreement (EULA) will open.
Check “I accept the terms in the License Agreement.”
Select “Next.”
License
Step 4: Set Download Path
At last, it will ask for a "Destination Folder" where all the files and their utility will be saved,
provide the path where you want to install NodeJS and then click on [Link]
Or, if you wish to perform "Custom Setup", click on Change and choose
your desired path.
Then, select “Next”
Custom Setup
Step 5: Get the System Ready to Complete the Setup
The installer may prompt you to “install tools for native modules”.
Select “Install”
System Ready
Do not close or cancel the installer until the installation is complete.
Complete the NodeJS Setup Wizard.
Click “Finish.”
How to Download and Install [Link] and NPM
Step 6: Verify the Installation
Once the installation is complete, you can verify that both NodeJS and NPM are installed
correctly by running the following commands in your terminal or command prompt:
Verify NodeJS Installation:
node -v
This command will display the installed version of NodeJS.
Verify NPM Installation:
npm -v
This command will display the installed version of NPM.
Node and npm
If both commands return the version numbers, it means that NodeJS and NPM are
successfully installed on your system.
Start creating your NodeJS application.
WORKING WITH NODE PACKAGES:
1. What is [Link] ?
[Link] is a special file that describes your [Link] project.
It contains information about your app, such as its name, version, dependencies, scripts, and
more.
This file is essential for managing and sharing [Link] projects, especially when using npm
(Node Package Manager).
WORKING WITH NODE PACKAGES:
[Link] uses NPM (Node Package Manager) to manage packages or modules, which are
reusable pieces of code that enhance the functionality of your application. NPM is
automatically installed with [Link] and provides commands to install, update, and manage
these packages.
Setting Up a [Link] Project
To start using NPM, first ensure [Link] and NPM are installed. Verify the installation by
running:
node -v
npm -v
Next, initialize a new project by creating a [Link] file:
npm init -y
This file stores metadata about your project, including dependencies.
Installing Packages
To install a package locally (specific to your project), use:
npm install <package-name>
For example, to install the Express framework:
npm install express
This creates a node_modules folder and updates [Link] with the dependency.
To install a package globally (available across all projects), use:
npm install -g <package-name>
Using Installed Packages
After installation, you can use the package in your project. For example, with Express:
const express = require('express');
const app = express();
[Link]('/', (req, res) => {
[Link]('Hello, World!');
});
[Link](3000, () => {
[Link]('Server running at [Link]
});
Run the application with:
node [Link]
Managing Dependencies
To install all dependencies listed in [Link], run:
npm install
To install a package as a development dependency (used only during development):
npm install <package-name> --save-dev
Updating and Uninstalling Packages
To update all packages to their latest compatible versions:
npm update
To update a specific package:
npm update <package-name>
To uninstall a package:
npm uninstall <package-name>
For global packages:
npm uninstall -g <package-name>
Version Management
To install a specific version of a package:
npm install <package-name>@<version>
For example:
npm install express@4.17.1
You can also use semantic versioning in [Link] to specify version ranges.
Best Practices
Use semantic versioning to ensure consistent environments.
Regularly audit dependencies with:
npm audit
Avoid publishing sensitive information like API keys in your packages.
NPM simplifies dependency management, making it an essential tool for [Link]
development. It supports local and global installations, version control, and automation
scripts, enhancing the development workflow.
Packages vs. Modules: The Building Blocks of npm
Packages: A package typically consists of a collection of code often comprising
JavaScript files along with a [Link] file. This particular file serves as the
package identification card encompassing details such as its name, version number,
dependencies, and scripts for project management. Packages range in scope from
utility functions to comprehensive web application frameworks such, as React or
Angular.
Modules: A module is, like a JavaScript file that offers a particular reusable function.
Modules make use of the require() function to bring in code from modules and utilize
the exports object to showcase their own functionality. They promote organized and
easily maintainable code.
Package Scopes: Organizing Your Packages
Scopes provide a way to namespace your packages. They're particularly important for larger
projects or those developed within organizations.
Unscoped Packages: [ For Simplicity ] Living in the global namespace, these
packages demand unique names to avoid conflicts. They are often used for smaller-
scale or experimental projects.
Scoped Packages: [ Fine Grained Control ] Scoped packages are identified by an @
symbol followed by the scope name (e.g., @mygeekorganization/utils). Scoping lets
you have multiple packages with the same name as long as they reside in different
scopes.
Public vs. Private Packages: Controlling Access
Public Packages: Public packages available on the npm registry encourage
collaboration in open source projects. Support community driven development. They
provide a platform, for sharing code with a wide range of users.
Private Packages: Private packages, which require a paid npm subscription are
intended for situations where code needs to be kept within an organization or
business. These packages are often utilized for software, confidential codebases or
packages, in the initial stages of development.
Public Packages: The Heart of Open-Source
Private packages necessitate a paid npm membership. Are designed for code that requires
privacy. Companies frequently utilize them for software or, in the initial stages of internal
project development.
Scope, Access Level, and Visibility: Explained
Unscoped Scoped
Feature Packages Packages
Scope Global Organizational
Access Level Always Public Public / Private
Visibility Public Registry Public / Private
Naming package-name @scope/package-name
Publishing(Default) npm publish npm publish
Publishing (public scoped) Not applicable npm publish --access public
Features
Large ecosystem of packages: npm has a vast ecosystem of open-source packages
that cater to a wide range of functionalities.
Dependency management: npm helps you manage project dependencies efficiently.
It tracks the exact versions of packages required by your project and ensures
compatibility.
Version control: npm allows you to specify the version of a package you want to
install. This helps to ensure that your project works consistently across different
environments.
Offline usage: npm allows you to cache downloaded packages. This means that you
can install packages even when you are not connected to the internet.
Examples:
Installing a popular public package (Express Web Framework):
npm install express
Listing installed packages:
npm list
Updating a package:
npm update express
Using a package in your code
const express = require('express');
const app = express();
[Link]('/', (req, res) => {
[Link]('Hello, world!');
});
[Link](3000, () => {
[Link]('Server is listening on port 3000');
});
Using a React component ( Public scoped package):
import Button from '@mui/material/Button';
Publishing a private scoped package.
o Create and initialize a package with a [Link] file.
o Set the private field to true in [Link].
o Run npm publish -- the package will be published with private access.
USING NODE PACKAGE MANAGER:
Here’s a clear, complete guide on how to use Node Package Manager (npm) in [Link],
with runnable examples.
1. What is npm?
npm is the default package manager for [Link].
It lets you install, update, and manage third-party libraries (packages) and your own
project dependencies.
It comes pre-installed with [Link].
2. Check if npm is installed
Bash
Copy code
node -v # Check [Link] version
npm -v # Check npm version
3. Initialize a [Link] project
Bash
Copy code
mkdir myproject
cd myproject
npm init -y # Creates [Link] with default values
[Link] stores project metadata and dependencies.
4. Installing Packages
Install a package locally
Bash
Copy code
npm install lodash
Adds lodash to node_modules/ and updates [Link] & [Link].
Install a package globally
Bash
Copy code
npm install -g nodemon
Installs nodemon globally so you can run it from anywhere.
5. Using Installed Packages
Example: Using lodash in a [Link] script.
Javascript
Copy code
// [Link]
const _ = require('lodash');
// Example: Chunk an array into smaller arrays
const arr = [1, 2, 3, 4, 5, 6];
const chunked = _.chunk(arr, 2);
[Link]('Original:', arr);
[Link]('Chunked:', chunked);
Run:
Bash
Copy code
node [Link]
6. Removing Packages
Bash
Copy code
npm uninstall lodash
7. Updating Packages
Bash
Copy code
npm update lodash
8. Running Scripts from [Link]
Edit [Link]:
Json
Copy code
"name": "myproject",
"version": "1.0.0",
"scripts": {
"start": "node [Link]",
"dev": "nodemon [Link]"
Run:
Bash
Copy code
npm run start
npm run dev
9. Installing All Dependencies
If you clone a project with a [Link]:
Bash
Copy code
npm install
This installs everything listed under "dependencies" and "devDependencies".
Best Practices
Always commit [Link] and [Link] to version control.
Use --save-dev for development-only packages:
Bash
Copy code
npm install jest --save-dev
Avoid committing node_modules/ to Git.
Package in [Link]
A package in NodeJS is a reusable module of code that adds functionality to your application.
It can be anything from a small utility function to a full-featured library.
Packages can be installed from the NPM registry.
They are stored in the node_modules folder in your project.
You can easily install, update, or remove packages with NPM commands.
How to Use NPM with NodeJS?
To start using NPM in your project, follow these simple steps
Step 1: Install NodeJS and NPM
First, you need to install NodeJS. NPM is bundled with the NodeJS installation.
Note: You can follow our article to Install the Node and NPM- How to install Node on your
system
Step 2: Verify the Installation
After installation, verify NodeJS and NPM are installed by running the following commands
in your terminal:
node -v
npm -v
These commands will show the installed versions of NodeJS and NPM.
NodeJS NPM Version
Step 3: Initialize a New NodeJS Project
In the terminal, navigate to your project directory and run:
npm init -y
This will create a [Link] file, which stores metadata about your project, including
dependencies and scripts.
Step 4: Install Packages with NPM
To install a package, use the following command
npm install <package-name>
For example, to install the [Link] framework
npm install express
This will add express to the node_modules folder and automatically update the [Link]
file with the installed package information.
Step 5: Install Packages Globally
To install packages that you want to use across multiple projects, use the -g flag:
npm install -g <package-name>
Step 6: Run Scripts
You can also define custom scripts in the [Link] file under the "scripts" section. For
example:
"scripts": {
"start": "node [Link]"
Then, run the script with
npm start
Using NPM Package in the project
Create a file named [Link] in the project directory to use the package
//[Link]
const express = require('express');//import the required package
const app = express();
[Link]('/', (req, res) => {
[Link]('Hello, World!');
});
[Link](3000, () => {
[Link]('Server running at [Link]
});
express() creates an instance of the Express app.
[Link]() defines a route handler for HTTP GET requests to the root (/) URL.
[Link]() sends the response “Hello, World!” to the client.
[Link](3000) starts the server on port 3000, and [Link]() outputs the server
URL.
Now run the application with
node [Link]
Visit [Link] in your browser, and you should see the message: Hello, World!
Managing Project Dependencies
1. Installing All Dependencies
In a NodeJS project, dependencies are stored in a [Link] file. To install all
dependencies listed in the file, run:
npm install
This will download all required packages and place them in the node_modules folder.
2. Installing a Specific Package
To install a specific package, use:
npm install <package-name>
You can also install a package as a development dependency using:
npm install <package-name> --save-dev
Development dependencies are packages needed only during development, such as testing
libraries.
To install a package and simultaneously save it in [Link] file (in case using NodeJS),
add --save flag. The --save flag is default in npm install command so it is equal to npm
install package_name command.
Example:
npm install express --save
Usage of Flags:
--save: flag one can control where the packages are to be installed.
--save-prod : Using this packages will appear in Dependencies which is also by
default.
--save-dev : Using this packages will get appear in devDependencies and will only be
used in the development mode.
Note: If there is a [Link] file with all the packages mentioned as dependencies already,
just type npm install in terminal
3. Updating Packages
You can easily update packages in your project using the following command
npm update
This will update all packages to their latest compatible versions based on the version
constraints in the [Link] file.
To update a specific package, run
npm update <package-name>
4. Uninstalling Packages
To uninstall packages using npm, follow the below syntax:
npm uninstall <package-name>
For uninstall Global Packages
npm uninstall package_name -g
Popular NPM Packages for NodeJS
NPM has a massive library of packages. Here are a few popular packages that can enhance
your NodeJS applications
Packages Description
Express A fast, minimal web framework for building APIs and web applications.
Packages Description
Mongoose A MongoDB object modeling tool for NodeJS.
Lodash A utility library delivering consistency, customization, and performance.
Axios A promise-based HTTP client for making HTTP requests.
React A popular front-end library used to build user interfaces.
Dotenv Loads environment variables from a .env file into [Link].
Automatically restarts the server during development when file changes are
Nodemon
detected.
A JavaScript testing framework designed to ensure correctness of any
Jest
NodeJS code.
Enables real-time, bidirectional communication between web clients and
[Link]
servers.
Versioning in NPM
NPM allows you to manage package versions. This is important when you want to ensure that
a specific version of a library is used across all environments.
Install a Specific Version
To install a specific version of a package, use:
npm install <package-name>@<version>
For example:
npm install express@4.17.1
This will install version 4.17.1 of Express, regardless of the latest version.
Using Semantic Versioning to manage packages
To install a package of a specific version, mention the full and exact version in the
[Link] file.
To install the latest version of the package, mention "*" in front of the dependency or
"latest". This will find the latest stable version of the module and install it.
To install any version (stable one) above a given version, mention it like in the
example below: "express":"^4.1.1". in [Link] file. The caret symbol (^) is
used to tell the npm to find a version greater than 4.1.1 and install it.
Dependencies vs DevDependencies
Aspects Dependencies DevDependencies
Required for running the Required only during
Purpose application in the production. development(not in production).
Examples express, mongoose, lodesh, nodemon, eslint, jest, moch,
Aspects Dependencies DevDependencies
react, axios webpack, babel
Installed using:
Installed using:
npm install <package name>
npm install <package> --save-dev
or
(or- D)
Installation npm install <package> --save
Location in
Listed under "dependencies" key listed under "devDependencies" key
[Link]
Yes, included when you run npm No, ignored when you run npm
Availability install --production. install --production.
Directly required for the app to used for development tools,testing,
function(e.g - web frameworks, linting, bundling, but not for
Impact on App database drivers etc) running the app live.
Command on
npm install express npm install nodemon --save-dev
Example
Creating Console-based Node Application
1. Running NodeJS with Console (No Setup Required)
NodeJS allows developers to run JavaScript directly in the console without any setup. We can
start the NodeJS REPL (Read-Eval-Print Loop) by simply typing node in the terminal and
running JavaScript commands interactively.
$ node
> let name = "Jiya";
> [Link]("Hello, " + name + "!");
Output
Node First Application
Creating Application with npm init and Installed Modules
Step 1: Initialize a NodeJS Project
mkdir my-node-app
cd my-node-app
npm init -y
Step 2: Install Required Modules
We will install fs (for handling file operations) and path (for working with file paths).
npm install fs path
Step 3: Create an [Link] File
Create a simple HTTP server that reads and serves a file.
import http from "http";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath([Link]);
const __dirname = [Link](__filename);
const server = [Link]((req, res) => {
const filePath = [Link](__dirname, "[Link]");
[Link](filePath, "utf8", (err, data) => {
if (err) {
[Link](500, { "Content-Type": "text/plain" });
[Link]("Error reading file");
} else {
[Link](200, { "Content-Type": "text/plain" });
[Link](data);
});
});
[Link](3000, () => {
[Link]("Server is running on port 3000");
});
Step 4: Create a [Link] File
Create a [Link] file in the same directory and add some content:
Hello, this is a [Link] application without Express!
Step 5: Run the Application
node [Link]
Creating Web-based Node Application
A web-based Node application consists of the following three important components:
Import required module
Create server
Read Request and return response
Let us learn more about them in detail
Step 1: Import required modules
Load Node modules using the required directive. Load the http module and store the returned
HTTP instance into a variable.
Syntax:
var http = require("http");
Step 2: Creating a server in Node
Create a server to listen to the client's requests. Create a server instance using
the createServer() method. Bind the server to port 8080 using the listen method associated
with the server instance.
Syntax:
[Link]().listen(8080);
Step 3: Read request and return response in Node
Read the client request made using the browser or console and return the response. A function
with request and response parameters is used to read client requests and return responses.
Syntax:
[Link](function (request, response) {...}).listen(8080);
step 4: Create an [Link] File
var http = require('http');
[Link](function (req, res) {
[Link](200, {'Content-Type': 'text/html'});
[Link]('Hello World!');
}).listen(8080);
Step 5: To run the program type the following command in terminal
node [Link]
Output:
Core Components of a Node-First Application
Backend (NodeJS with [Link]/NestJS/[Link]): The backend serves as the core
processing unit, handling API requests, database interactions, and authentication
mechanisms.
Database (MongoDB, PostgreSQL, MySQL, Redis): A Node-First approach
commonly utilizes NoSQL databases like MongoDB for scalability, though SQL
databases like PostgreSQL or MySQL are also widely used.
Frontend (React, [Link], Angular): Although frontend technologies can vary,
JavaScript frameworks like [Link], [Link], and Angular work seamlessly with a
SNode-powered backend.
Authentication & Security: Utilizing JWT (JSON Web Tokens), OAuth, or session-
based authentication ensures secure user interactions.
Real-Time Capabilities ([Link], WebRTC): For real-time applications like chat
apps or live updates, [Link] provides seamless WebSocket communication.