0% found this document useful (0 votes)
19 views41 pages

4-2-Node JS

The document provides a comprehensive overview of Node.js, including its introduction, environment setup, key concepts like callbacks, events, and packaging, as well as the Express framework and RESTful API development. It covers installation steps, basic programming examples, and the advantages of using Node.js and Express.js for web application development. Additionally, it explains the principles of RESTful APIs and includes examples of HTTP methods used in REST.

Uploaded by

vibhavbhartiya13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views41 pages

4-2-Node JS

The document provides a comprehensive overview of Node.js, including its introduction, environment setup, key concepts like callbacks, events, and packaging, as well as the Express framework and RESTful API development. It covers installation steps, basic programming examples, and the advantages of using Node.js and Express.js for web application development. Additionally, it explains the principles of RESTful APIs and includes examples of HTTP methods used in REST.

Uploaded by

vibhavbhartiya13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

INTRODUCTION,

ENVIRONMENT SETUP,
Node.js REPL TERMINAL,
NPM (NODE PACKAGE MANAGER)
CALLBACKS CONCEPT,
EVENTS,
PACKAGING,
EXPRESS FRAMEWORK,
RESTFUL API.
Introduction

• Node.js is a powerful tool for controlling servers, building web


applications, and creating event-driven programs.
• Takes JavaScript—a language familiar to all web developers—out
of the browser.
• With Node.js, the applications can run on laptop or even the cloud.
• It is an open-source server side runtime environment built on
Chrome's V8 JavaScript engine.
• Node.js was written and introduced by Ryan Dahl in 2009.
Node.js
◦Provides an event driven, non-blocking (asynchronous) I/O and cross-
platform runtime environment for building highly scalable server-side
applications using JavaScript.
◦ Can be used to build different types of applications such as command line
application, web application, real-time chat application, REST API server etc.
◦Mainly used to build network programs like web servers, similar to PHP, Java,
or ASP.NET.
◦The Node.js Foundation was formed in 2015. The Foundation is made up of
several large companies, including IBM, Microsoft, PayPal and many, many
others. And it's a collaborative project at the Linux Foundation.
◦It’s called Node because it is used to build
simple single-process blocks called nodes.

◦These nodes can be organized with good


networking protocols for communication with
each other and be scaled up to build large
distributed programs.
Advantages of Node.js

1.Its an open-source framework under MIT license.


2.Uses JavaScript to build entire server side application.
3.Lightweight framework that includes bare minimum
modules. Other modules can be included as per the need
of an application.
4.Asynchronous by default. So it performs faster than other
frameworks.
5.Cross-platform framework that runs on Windows, MAC or
Linux
Node.js Process Model

◦All the web application user will be handled by a


single thread and all the I/O work or long running job
is performed asynchronously for a particular request.
◦This single thread doesn't have to wait for the
request to complete and is free to handle the next
request.
◦ When asynchronous I/O work completes then it
processes the request further and sends the
response.
Environment Setup:
Install Node.js

◦The following tools/SDK are required for developing a


Node.js application on any platform.
1.Node.js
2.Node Package Manager (NPM)
3.IDE (Integrated Development Environment) or TextEditor

◦NPM (Node Package Manager) is included in Node.js


installation since Node version 0.6.0., so there is no need
to install it separately.
Install Node.js on Windows

◦Visit Node.js official web site https://nodejs.org. It will automatically detect


OS and display download link as per your Operating System.
◦For example, it will display following download link for 64 bit Windows OS.
Verify Installation

◦Once you install Node.js on your computer, you can verify it by opening the command
prompt and typing node -v.
◦If Node.js is installed successfully then it will display the version of the Node.js
installed on your machine, as shown below.

Node.js Console/REPL

◦ Node.js comes with virtual environment called REPL (or Node shell).
◦ REPL stands for Read-Eval-Print-Loop.
◦ It is a quick and easy way to test simple Node.js/JavaScript code.
◦ To launch the REPL (Node shell), open command prompt (in Windows) and
type node as shown below. It will change the prompt to > in Windows
Some ex: Define Variables on REPL

define a function and execute it as shown below.

To exit from the REPL terminal, press Ctrl + C twice or write .exit and press Enter.
This will return back to command prompt.
The following table lists important REPL commands.

REPL Command Description


.help Display help on all the commands
tab Keys Display the list of all commands.
Up/Down Keys See previous commands applied in REPL.
.save filename Save current Node REPL session to a file.
.load filename Load the specified file in the current Node REPL
session.
ctrl + c Terminate the current command.
ctrl + c (twice) Exit from the REPL.
ctrl + d Exit from the REPL.
.break Exit from multiline expression.
.clear Exit from multiline expression.
NPM (Node Package Manager)
◦command line tool that installs, updates or uninstalls Node.js packages in our
application.
◦It is also an online repository for open-source Node.js packages.
◦Official website: https://www.npmjs.com
◦NPM is included with Node.js installation.
◦Verify NPM installation by writing:

• NPM performs the operation in two modes: global and local.

-global mode: Operations affect all Node.js applications on the computer.


- local mode: Operations are specific to the current project directory.
Install Package Locally
Use the following command to install any third party module in your local folder:

For example: install ExpressJS into


c:\practice\NODEJS folder.

- All the modules installed using NPM are installed under node_modules folder.

- ExpressJS folder is created under node_modules folder in the root folder of our project, here in
c:\practice\NODEJS folder and install Express.js there.
--- To install ExpressJS and
also adds dependency
entry into the
package.json:

--- To uninstall ExpressJS from the application:


c:\practice\NODEJS> npm uninstall express

--- npm install -g express: This command will install Express.js


globally, and then can be accessed in any
project using : equire('express’)
An external JavaScript file
Executed by using the node fileName command.
Ex: To runs firstnjs.js on command prompt/terminal & displays
result:

firstnjs.js
console.log("Namaste World!!!");
Node.js Basics

Primitive Types
• String
• Number
• Boolean
• Undefined
• Null
• RegExp
◦Everything else is an object in Node.js.

Loose Typing
◦Use var keyword to declare a variable of any type.
Callbacks
◦A callback is a function passed as an argument to another
function.
◦It is executed after the main function completes its task.
◦Used extensively in asynchronous programming.
◦Helps in non-blocking code execution.
Importance of Callbacks:
• Enables execution of time-consuming/heavy tasks without
stopping other operations.Faster response time.
• Efficient handling of I/O operations, file reading, network
requests, etc.
• Handles multiple tasks simultaneously, enhancing
performance.
Program: Reading a File Asynchronously

const fs = require('fs'); Understanding the Example Code

fs.readFile('sample.txt', 'utf8', (err, data) => 1. Import fs (File System) module.


{ 2. Use fs.readFile() with three
if (err) {
console.error("Error reading the file:", parameters:File name
err); (sample.txt)Encoding (utf8)Callback
return;
function with err and data arguments.
}
console.log("File content:", data); 3. In the callback, handle:
}); Errors - Print error if it occurs.
Data - Print file content if read
console.log("Reading file...");
successfully.
In output: Reading file...
"Reading file..." is printed first.
File content: Hello,
After file read is complete, the callback prints File
content: .... Node.js
Events in Node.js
• In Node.js, an "event" is an action or occurrence that is detected by the
program. For example, clicking a button, a server receiving a request,
or a timer expiring are all events.
• Provides an EventEmitter class to manage and handle these events.

Key Concepts of Events


1. EventEmitter Class: This is a core class in Node.js that allows us to
create, listen to, and respond to custom events.
2. on(event, listener): This function registers a listener (callback) that
will be called whenever the specified event is emitted.
3. emit(event): This function triggers an event, causing any listeners
that are listening to that event to execute.
Program Next>>
// Step 1: Import the events module in Node.js
const EventEmitter = require('events');
Output:
// Step 2: Create an EventEmitter object
const eventEmitter = new EventEmitter(); Hello! This is
your first
// Step 3: Set up an event listener: We create an event
event in
called 'sayHello' that will print a message when
triggered Node.js.

eventEmitter.on('sayHello', () => {
console.log('Hello! This is your first event in
Node.js.');
});

// Step 4: Emit (trigger) the event


eventEmitter.emit('sayHello');
Packaging
1. Creating and managing reusable pieces of code, called
packages or modules.

2. These packages can be shared and installed, making it


easier to organize and reuse code across different projects.

3. Packages are often used to add functionality (like handling


databases, file systems, or web requests) to our Node.js
applications without needing to code everything from
scratch.
Key Concepts of Packaging in Node.js

Package : A package is a collection of files (code) that provide certain


functionalities.
For example- used for database operations, web servers, or math
utilities.

npm (Node Package Manager): npm is a tool that helps to find,


install, and manage Node.js packages. It has a vast online library of
packages that we can use in your projects.

package.json File: This file is the "heart" of any Node.js project. It


contains information about the project, like its name, version,
description, dependencies (other packages it needs), and scripts.
Prog. 1: To provide some colored text
Install chalk: npm install chalk
const chalk = require('chalk');
// After change program will ae as:
// Output some colored text
console.log(chalk.blue('Hello, World!'));
console.log(chalk.green('This is a beginner- import chalk from 'chalk';
friendly program!'));
console.log(chalk.red.bold('Error: Something console.log(chalk.green('Hello,
went wrong!')); World!'));

• If an error comes, then Switch to ES Modules


• Rename your file to .mjs: Rename pack1.js to pack1.mjs to indicate it's an ES module.
• Use import instead of require
OR
• Update package.json: Add "type": "module" to your package.json:
{
"type": "module“ }
• Change require to import: Update your script (pack1.js) to use import.
• Run the script:node pack1.js
Express.js
• is a minimal and flexible Node.js web application framework
• helps to create servers and handle HTTP requests easily.
• Provides various features that make web application
development fast and easy which otherwise takes more
time using only Node.js.

Express.js is based on the Node.js middleware module called


connect which in turn uses http module.
So, any middleware which is based on connect will also work
with Express.js.
Advantages of
Express.js
• Makes Node.js web application development fast and easy.
• Easy to configure and customize.
• define routes of application based on HTTP methods and URLs.
• Includes various middleware modules which can be used to
perform additional tasks on request and response.
• Easy to integrate with different template engines like Jade, Vash,
EJS etc.
• Allows to define an error handling middleware.
• Easy to serve static files and resources of your application.
• Allows to create REST API server.
• Easy to connect with DBs such as MongoDB, Redis, MySQL
Step 1: Set Up Your Express Project

1. Install Node.js: Ensure that Node.js is installed on your


system.

2. Create a New Project Directory: mkdir express-app


cd express-app
3. Initialize NPM:npm init -y

This will create a package.json file.

npm install express


4. Install Express:
Step 2: Build a Basic Express
Application
Prog 1. Create a file named index.js and write a basic Express server:
const express = require('express');
const app = express();// creates Express app.
const PORT = 3000;
// app object defines a route for home page (`/`).
app.get('/', (req, res) => {
res.send('Welcome to Express!'); // sends a response to browser
});

// starts the server on port 3000.


app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});

2. To run node index.js 3. To see output in browser:


server: http://localhost:3000
Configure Routes
Use app object to define different routes of your application. The app
object includes get(), post(), put() and delete() methods to define
routes for HTTP GET, POST, PUT and DELETE requests respectively.

The following example demonstrates configuring routes for HTTP


requests.
Prog-2: To handle HTTP POST request and get data from the
submitted form:
We'll make these two
files:
1. index.html: Separate file for the HTML
form.
<html> <head>
<title>Form Submission</title> </head>
<body>
<h2>Form Submission</h2>
<form action="/submit" method="POST">
Name:<input type="text" name="name" required>
<br><br>
Age:<input type="number" id="age" name="age" required>
<br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>

2. app1.js: Main server file for backend


logic.
2. app1.js: Main server file for backend logic.
const express = require('express'); // Start the server
const PORT = 3000;
const path = require('path'); app.listen(PORT, () => {
const app = express(); console.log(`Server running
// Middleware to parse form data at http://localhost:${PORT}`);
app.use(express.urlencoded({ extended: true })); });

// Route to serve the HTML form


app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
}); To see output:
// Route to handle form submission
1. Start the server:
app.post('/submit', (req, res) => { node app.js
const { name, age } = req.body; // Extract form
data 2. Open your browser
and go to:
res.send(`<h2>Data Received</h2><p>Name: $ http://localhost:3000
{name}</p><p>Age: ${age}</p>`);
});
RESTful API
A RESTful API (Representational State Transfer) is an architectural style for designing
networked applications. It uses HTTP requests to perform CRUD (Create, Read, Update,
Delete) operations on resources, where each resource is identified by a unique URI
(Uniform Resource Identifier).
RESTful APIs follow these principles:
1.Stateless: Each request from a client to the server must contain all the information needed
to understand the request (e.g., authentication tokens, parameters). The server should not
store any session information between requests.
2.Client-Server: The client and server are separate entities, allowing them to evolve
independently.
3.Cacheable: Responses should define caching rules to improve performance.
4.Uniform Interface: REST uses standard HTTP methods and status codes, making it
intuitive and easy to use.
5.Layered System: A client can interact with a server via an intermediary (proxy, load
balancer, etc.) without needing to know about the layers involved.
HTTP Methods in REST
•GET: Retrieve data (e.g., get a list of users or a single user).
•POST: Create a new resource (e.g., create a new user).
•PUT: Update an existing resource (e.g., update user
information).
•DELETE: Remove a resource (e.g., delete a user).

We can build RESTful APIs using various frameworks & languages,


including: •Flask (Python)
•Django (Pythn)
•Spring Boot (Java)
Example
const express = require('express');
const app = express();
// Middleware to parse JSON request bodies
app.use(express.json());
// RESTful API example
let users = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 }
];
// GET /users - Get all users
app.get('/users', (req, res) => {
res.status(200).json(users);
});
// GET /users/:id - Get a single user by ID
app.get('/users/:id', (req, res) => {
const userId = parseInt(req.params.id);
const user = users.find(u => u.id === userId);
if (user) {
res.status(200).json(user);
} else {
res.status(404).json({ message: 'User not found' });
}
});
const newUser = {
id: users.length + 1, name, age
};
users.push(newUser);
res.status(201).json(newUser);
});
app.put('/users/:id', (req, res) => {// PUT /users/:id - Update an existing user
const userId = parseInt(req.params.id);
const { name, age } = req.body;
const user = users.find(u => u.id === userId);
if (user) {
user.name = name;
user.age = age;
res.status(200).json(user);
} else {
res.status(404).json({ message: 'User not found' });
}
});
app.delete('/users/:id', (req, res) => {// DELETE /users/:id - Delete a user by ID
const userId = parseInt(req.params.id);
users = users.filter(u => u.id !== userId);
res.status(200).json({ message: 'User deleted successfully' });
});
const port = 3000;
app.listen(port, () => {// Start the server
Uses of RESTful APIs:
• use standard HTTP methods for easier clients &servers
communication.
• is stateless, meaning each request is independent.
• allows communication b/w different technologies & platforms
(e.g., mobile apps, websites, IoT devices, databases).
• simple to use and understand, making it easier to build APIs.
• HTTP responses can be cached to improve performance.
• Reduces the need for complex server-side session management,
improving speed and responsiveness.
How Express.js and RESTful API Work
Together?
Express.js is a framework that is commonly used to build
RESTful APIs :
• Express allows to define routes for handling different HTTP
methods (GET, POST, PUT, DELETE).

• Express handles incoming HTTP requests, processes the


data, and sends back responses, typically in JSON format for
APIs.

• Express provides middleware functions that can handle


tasks like request parsing (e.g., handling JSON or form data)
before reaching the actual route handler.
In Short:

• Express.js is a framework for building web


applications and APIs quickly and efficiently using
Node.js.
• RESTful APIs allow different systems to communicate
over the web using standard HTTP methods.
• Express.js is an ideal choice for building RESTful APIs
because it simplifies routing, middleware
management, and data handling.
• Express makes it easy to create APIs, and REST
provides a simple architecture to follow for web
services
Web services

 allow different systems to communicate and


share data over the internet.
 They are based on standards such as HTTP and
data formats like XML or JSON.
 SOAP and REST are the two most common types
of web services.
 Web services make applications more flexible,
scalable, and easy to integrate.
Create a very simple RESTful API to manage a list of users.
Prog. 1 Create a basic Express app (app.js)
Prog. 2 GET request to fetch all users

Prog. 3 GET request to fetch a single user by ID

Prog. 4 POST request to create a new user

Prog. 5 PUT request to update an existing user

Prog. 6 DELETE request to remove a user

• RESTful API allows communication between systems using HTTP


methods.
• CRUD Operations can be implemented via HTTP methods like GET, POST,
PUT, DELETE.
• A simple Node.js and Express server can be used to create a

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy