0% found this document useful (0 votes)
20 views

Unit 3

Node.js is a JavaScript runtime environment built on Chrome's V8 JavaScript engine. It allows JavaScript to be run on the server-side. Some key points: - Node.js was created by Ryan Dahl in 2009 and uses an event-driven, non-blocking I/O model making it lightweight and efficient for data-intensive real-time applications. - It uses a single-threaded event loop model that makes it highly scalable and able to support thousands of concurrent connections with a single process. - Node.js is commonly used for building fast and scalable network applications such as web servers and APIs. It provides a rich library of modules for various tasks like file system access,

Uploaded by

racawo8208
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)
20 views

Unit 3

Node.js is a JavaScript runtime environment built on Chrome's V8 JavaScript engine. It allows JavaScript to be run on the server-side. Some key points: - Node.js was created by Ryan Dahl in 2009 and uses an event-driven, non-blocking I/O model making it lightweight and efficient for data-intensive real-time applications. - It uses a single-threaded event loop model that makes it highly scalable and able to support thousands of concurrent connections with a single process. - Node.js is commonly used for building fast and scalable network applications such as web servers and APIs. It provides a rich library of modules for various tasks like file system access,

Uploaded by

racawo8208
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/ 95

Node.

js

• Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8 Engine).
• Node.js was developed by Ryan Dahl in 2009.
• It is for easily building fast and scalable network applications.
• Node.js uses an event-driven, non-blocking I/O model.
• that makes it lightweight and efficient, perfect for data-intensive applications that run across
distributed devices.
• Node.js is an open source, cross-platform runtime environment for developing server-side and networking
applications.

• Node.js applications are written in JavaScript


• It can be run within the Node.js runtime on OS X, Microsoft Windows, and Linux.
• Node.js also provides a rich library of various JavaScript modules.
• “Node.js = Runtime Environment + JavaScript Library”
Features of Node.js

Asynchronous and Event Driven


Very Fast
Single Threaded but Highly Scalable
License − Node.js is released under the MIT license
Who use Node.js
Where to Use Node.js

Where Not to Use Node.js


It is not advisable to use Node.js for CPU intensive applications
Node.js Server Architecture
Node.js uses the “Single Threaded Event Loop” architecture to handle multiple concurrent
clients. Node.js Processing Model is based on the JavaScript event-based model along with
the JavaScript callback mechanism.
Parts of the Node.js Architecture:
• Requests
Incoming requests can be blocking (complex) or non-blocking (simple), depending upon the tasks that a user
wants to perform in a web application
• Node.js Server
Node.js server is a server-side platform that takes requests from users, processes those requests, and returns
responses to the corresponding users
• Event Queue
Event Queue in a Node.js server stores incoming client requests and passes those requests one-by-one into the
Event Loop
• Thread Pool
Thread pool consists of all the threads available for carrying out some tasks that might be required to fulfill client
requests
• Event Loop
Event Loop indefinitely receives requests and processes them, and then returns the responses to corresponding
clients
• External Resources
External resources are required to deal with blocking client requests, external resources are used. They can be of
any type (computation, storage, etc).
Architecture
The Workflow of Node.js Architecture:
A web server developed using Node.js typically has a workflow that is quite similar to the
diagram illustrated below. Let’s explore this flow of operations in detail.

Fig: Node.js Architecture Workflow


• Clients send requests to the webserver to interact with the web application. Requests
can be non-blocking or blocking:
-Querying for data
-Deleting data
-Updating the data

• Node.js retrieves the incoming requests and adds those requests to the Event Queue
• The requests are then passed one-by-one through the Event Loop. It checks if the
requests are simple enough to not require any external resources
• Event Loop processes simple requests (non-blocking operations), such as I/O Polling,
and returns the responses to the corresponding clients
A single thread from the Thread Pool is assigned to a single complex request. This thread is
responsible for completing a particular blocking request by accessing the external resources,
such as compute, database, file system, etc.
Once, the task is carried out completely, the response is sent to the Event Loop that in turn
sends that response back to the Client
A Node.js application consists of the following three important
components −

• Import required modules − We use


the require directive to load Node.js modules.
• Create server − A server which will listen to
client's requests similar to Apache HTTP Server.
• Read request and return response − The server
created in an earlier step will read the HTTP
request made by the client which can be a
browser or a console and return the response.
Creating Node.js Application

Step 1 - Import Required Module


We use the require directive to load the http module and store the returned HTTP instance
into an http variable as follows −

var http = require("http");

Step 2 - Create Server


We use the created http instance and call http.createServer() method to create a server
instance and then we bind it at port 8081 using the listen method associated with the server
instance. Pass it a function with parameters request and response. Write the sample
implementation to always return "Hello World".
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});

// Send the response body as "Hello World"


response.end('Hello World\n');
}).listen(8081);

// Console will print the message


console.log('Server running at http://127.0.0.1:8081/');
The above code is enough to create an HTTP server which listens, i.e., waits for a request
over 8081 port on the local machine.
Step 3 - Testing Request & Response
Let's put step 1 and 2 together in a file called main.js and start our HTTP server as shown
below −
var http = require("http");

http.createServer(function (request, response) {


// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});

// Send the response body as "Hello World"


response.end('Hello World\n');
}).listen(8081);

// Console will print the message


console.log('Server running at http://127.0.0.1:8081/ /’);
Now execute the main.js to start the server as follows −
$ node main.js
Verify the Output. Server has started.
Server running at http://127.0.0.1:8081/
Open http://127.0.0.1:8081/ in any browser and observe the following result.
Initiate the Node.js File
To initialize a new Node.js project, you can use the npm init command.
This command will prompt you with a series of questions to create
a package.json file for your project.
The package.json file contains metadata about your project, such as its name, version, and
dependencies.
Here are the steps to initialize a new Node.js project:
1. Open your terminal and navigate to the directory where you want to create your
project.
2. Type npm init and press enter.
3. Answer the questions that appear in the terminal. You can press enter to accept the
default values or type in your own values.
4. Once you have answered all the questions, a package.json file will be created in your
project directory.
That’s it! You have successfully initialized a new Node.js project.

Go to the command line interface, write node myfirst.js and hit enter:
Node Module System

•The Node.js module system is a key feature that enables developers to organize,
encapsulate, and manage their code in a modular and efficient manner.
•It allows developers to break down their code base into smaller, reusable components
called modules, which can be shared and imported as needed.
•This system plays a crucial role in promoting code maintainability, reusability, and
collaboration in Node.js applications.

Node.js Built-in Modules


•Node.js provides a set of built-in modules known as core modules.
•These modules offer essential functionalities for a wide range of tasks, from working
with file systems to handling networking operations.
•You can use these modules in your Node.js applications without installing any
additional packages.
•Here are some of the most commonly used built-in core modules:
This wrapper function has 5 arguments: exports, require, module, __filename, and __dirname. This is
what makes them appear to look global when in fact they are specific to each module.

Resolving: To find the absolute path of the file.


Loading: To determine the type of the file content.
Wrapping: To give the file its private scope. This is what makes both the require and module objects local
to every file we require.
Evaluating: This is what the VM eventually does with the loaded code.
Caching: So that when we require this file again, we don’t go over all the steps another time.

All of these arguments get their values when Node executes the wrapper function. exports is defined as a
reference to module.exports prior to that. require and module are both specific to the function to be executed,
and __filename/__dirname variables will contain the wrapped module’s absolute filename and directory path.
fs (File System): This module provides methods for working with the file system,
allowing you to read, write, and manipulate files and directories.
//ex1:
const fs = require("fs");
let text = fs.readFileSync("dele.txt", "utf-8");
text = text.replace("browser", "Rohan");

console.log("The content of the file is");


console.log(text);

console.log("Creating a new file...");


fs.writeFileSync("rohan.txt", text);

//ex2
const fs = require("fs");
fs.readFile("dele.txt", "utf-8", (err, data) => {
console.log(err, data);
});
console.log("This is a message");
http: The http module is used for creating HTTP servers and making HTTP requests. It's the
foundation of building web applications and APIs.

const http = require("http");


const hostname = "127.0.0.1";
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end("Hello World");
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
path: The path module provides utilities for working with file paths, making it easier to
manipulate and join paths in a cross-platform manner.

Path.join takes an array of path segments and joins them together using the platform-
specific separator.This method is more reliable when compared to string concatenation
because of extra caution to be taken for supporting multiple platforms.

//join
console.log(path.join("folder1", "folder2", "index.html"));
console.log(path.join("/folder1", "folder2", "index.html"));
console.log(path.join("/folder1", "//folder2", "index.html"));
console.log(path.join("/folder1", "//folder2", "../index.html"));
console.log(path.join(__dirname, "data.json"));
//Path.dirname is a helper method to get the parent directory for the given path
var path = require("path");
// //Return the directries:
var directories = path.dirname("/Users/Refsnes/fg.js");
console.log(directories);

//Path module has a basename method to get the file name part
const path = require("path");

console.log(__filename);
console.log(__dirname);

//basename
console.log(path.basename(__filename));
console.log(path.dirname(__dirname));

//extname
console.log(path.extname(__filename));
console.log(path.extname(__dirname));
//parse
console.log(path.parse(__filename));
console.log(path.parse(__dirname));

//isabsolute
console.log(path.isAbsolute(__filename));
console.log(path.isAbsolute("./data.json"));
os (Operating System): This module provides information about the operating system's CPU, memory, network
interfaces, and other related details.

const os = require("os");
console.log(os);

console.log(os.freemem());
console.log(os.freemem() / (1024 * 1024 *
1024));
console.log(os.totalmem() / (1024 * 1024 *
1024));
console.log(os.hostname());
console.log(os.platform());
console.log(os.userInfo());
url: The url module offers utilities for parsing and formatting URLs.

const url = require("url");


const urlString = "https://www.google.com/path?
query=value";
const parsedUrl = url.parse(urlString, true);
console.log(parsedUrl.hostname); // Output:
www.google.com
console.log(parsedUrl.query); // Output:
{ query: 'value' }
console.log(parsedUrl.pathname);
querystring: This module provides methods for parsing and formatting query strings.

//Parse a query string into an object, and extract the year property:
const querystring = require("querystring");
//const queryString = "param1=value1&param2=value2";
const queryString = "ocid=msedgntp&cvid=6010b9ead85c42139a8749d3fc185e16&ei=9";
const parsedQuery = querystring.parse(queryString);
console.log(parsedQuery); // Output: { param1: 'value1', param2: 'value2' }
console.log(parsedQuery.cvid);

const url = require("url");


const urlString =
"https://www.msn.com/en-in/health/health-news/horoscope-today-
astrological-prediction-for-november-12-2023/ar-AA1jLU7m?
ocid=msedgntp&cvid=6010b9ead85c42139a8749d3fc185e16&ei=9";
const parsedUrl = url.parse(urlString, true);
console.log(parsedUrl.hostname); // Output: www.google.com
console.log(parsedUrl.query); // Output: { query: 'value' }
console.log(parsedUrl.pathname);
Creating a Module:
1. Create a JavaScript File: Start by creating a new .js file that will define your module. Let's call it math.js.
2. Define Module Functionality: In the math.js file, define the functionality you want to export. For example, let's create
a module that provides functions for addition and subtraction:
//math.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;

module.exports = {
add,
subtract,
};
Loading and Using the Module:
Require the Module: In another JavaScript file (let's call it main.js), you can use the require function to load the
math.js module:
// main.js
const mathModule = require("./mathx");

console.log(mathModule.add(5, 3));
console.log(mathModule.subtract(10, 4));

Run the Main File: Run the main.js file using Node.js:
node main.js

This will output the results of the addition and subtraction operations defined in the math.js module.
Remember that the require function takes the path to the module file as an argument. You can use either a relative path
(starting with ./) or an absolute path.
Exporting Different Types:
You can export various types of values from a module, including variables, functions, classes, or even an entire object. The
module.exports object allows you to define what parts of the module are accessible when the module is imported using require.

For example, exporting a single function from a module:


// myFunction.js
const myFunction = () => {
// Function implementation
};
module.exports = myFunction;

And importing it in another file:


// main.js
const importedFunction = require('./myFunction');
importedFunction();

This is the basic process of creating and loading a module in Node.js. By organizing your code into modules, you can maintain a
clean and modular codebase, reuse code efficiently, and improve collaboration among team members.
Global Object:
The global object provides access to various global properties and functions that are available throughout your application
without the need to import them explicitly. While this might sound similar to the global scope in a browser's JavaScript
environment, it's important to note that the Node.js global object is not as extensive as the browser's global scope.
Some commonly used properties and functions available on the Node.js global object:
1. Global Variables:
 global: This property refers to the global object itself. It's equivalent to this in the global scope.
2. Console:
 console: Provides methods for logging and interacting with the console.
 console.log(), console.error(), console.warn(), etc.
3. Timers:
 setTimeout(), setInterval(), setImmediate(): Functions to schedule asynchronous operations.
4.Buffers:
 Buffer: The Buffer class for working with binary data.
5.Paths and Directories:
 __dirname: The directory name of the current module.
 __filename: The full path to the current module file.
 require(): A function to import modules.
6.Process:
 process: Provides information and control over the current Node.js process.
 process.argv: An array containing command-line arguments.
 process.env: An object containing environment variables.
 process.cwd(): Returns the current working directory.
 process.exit(): Terminates the Node.js process.
7.Modules and Exports:
 module: A reference to the current module object.
 exports: An object used to define what a module exports.
8.Error Handling:
 Error: The constructor function to create error objects.
9.Utilities:
 setInterval(), setTimeout(): Functions for scheduling repeated or delayed execution of functions.
It's important to note that while these properties and functions are available globally, it's generally considered better practice
to avoid polluting the global scope and to use module-level scoping instead. This means that you often declare and use
variables, functions, and classes within the scope of a module, making them accessible only where needed. This approach
promotes better code organization, reusability, and maintainability.
For example, instead of using the global setTimeout(), you might use it within a specific modu// app.js
setTimeout(() => {
console.log('Delayed message');
}, 1000);
3Rd party example:-
const capitalize = require('capitalize)
And then you can use it in your code, like this for example:

const capitalize = require('capitalize')


console.log(capitalize("hello")) // Hello
Module.exports:-
Each file in a Node.js project is treated as a module that can export values to be
used by other modules.

module.exports is an object in a Node.js file that holds the exported values and
functions from that module.

Declaring a module.exports object in a file specifies the values to be exported


from that file. When exported, another module can import this values with the
require global method.

It is the object reference that gets returned from the require() calls.
It is automatically created by Node.js.
It is just a reference to a plain JavaScript object.
Exports alias
“exports” is just a convenience variable so module authors can write less code
Working with its properties is safe and recommended.
(eg.: exports.add = function…)
Exports is NOT returned by require()

module.exports vs exports in Node

module.exports = { value1, function1 }


or by using exports:

exports.value1 = value1
exports.function1 = function1
const function1 = function() {
const value1 = 50 console.log("I am a function")
exports.value1 = value1 }
module.exports = { function1, ...module.exports }
console.log(module)
// { console.log(module)
// id: ".",
// path: "...", // {
// exports: { value1: 50 }, // id: ".",
// parent: null, // path: "...",
// filename: "...", // exports: { function1: [Function: function1] },
// loaded: false, // parent: null,
// children: [], // filename: "...",
// paths: [ // loaded: false,
// ... // children: [],
// ], // paths: [
// } // ],
// }
Node Package
Manager(NPM)
NPM (Node Package Manager) is the default package manager for Node.js and
is written entirely in Javascript. Developed by Isaac Z. Schlueter, it was initially
released in January 12, 2010. NPM manages all the packages and modules for
Node.js and consists of command line client npm

Node Package Manager (NPM) is a command line tool that installs, updates or
uninstalls Node.js packages in your application.The node community around the
world creates useful modules and publishes them as packages in this repository.
It allows us to use code written by others easily without the need to write them
ourselves during development.
The required packages and modules in Node project are installed using NPM.
A package contains all the files needed for a module and modules are the JavaScript
libraries that can be included in Node project according to the requirement of the project.

NPM consists of two main parts:

a CLI (command-line interface) tool for publishing and downloading packages, and
an online repository that hosts JavaScript packages
Package Manager vs. Package Registry
A package manager is a tool developers use to automatically find, download, install, configure, upgrade, and
uninstall a computer's packages.

NPM (Node Package Manager) and Yarn (Yet Another Resource Negotiator) are two popularly used package
managers.

A package registry is a database (storage) for thousands of packages (libraries, plugins, frameworks, or tools).

In other words, a package registry is the place packages get published to and installed from.

NPM registry and GitHub Packages are two popularly used package registries.
To check the NPM version installed on your system, run:

npm -v

A package is a directory (or project) that has a package.json file used to record information about it.

NPM installation command


npm install package-name –save

the --save command above instructs NPM to save package-name in the package.json file as one of the
packages on which the project depends.

to install an exact version of a package


npm install [email protected] –save

The commands above will cause NPM to download three items into your project's root directory: a
node_modules folder, a package.json file, and a package-lock.json file
Global package installation
A globally installed package is a package that you can use anywhere on your system.

To install a package globally, run the code below on your terminal:

npm install package-name –g

You can do both local and global installation of packages you intend to use both on the command line
and in your project. Typical examples of such packages are ExpressJS and CoffeeScript.
Your package manager does not execute an installed package. NPM (and Yarn) only install packages to
the node_modules directory. And if you had specified the --save command, your manager would add
details about the package to the package.json file.
To execute (run) any executable package, you must explicitly do so yourself.
package.json
The package.json file is the heart of any Node project. It records important metadata about a project which is
required before publishing to NPM, and also defines functional attributes of a project that npm uses to install
dependencies, run scripts, and identify the entry point to our package

The package.json file helps us keep track of all the installed packages in a given project. When creating a
new project, it is important to start by creating this file.

How to Create a package.json File


Go to your project's root directory and initialize the creation of a package.json file by running:

npm init
The package.json file contains the metadata information. This metadata information in package.json file can
be categorized into below categories.

Identifying metadata properties: It basically consist of the properties to identify the module/project such as
the name of the project, current version of the module, license, author of the project, description about the
project etc.
Functional metadata properties: As the name suggests, it consists of the functional values/properties of the
project/module such as the entry/starting point of the module, dependencies in project, scripts being used,
repository links of Node project etc.

Advantages of a package.json File :-


It makes it possible to publish your project to the NPM registry
It makes it easy for others to manage and install your package
It helps NPM manage a module's dependencies easily
It makes your package reproducible and shareable with other developers
This command will create a package.json file. You will get prompts to provide the following information:

package-name: As you learned earlier in this tutorial, the name of your package must be unique. Also it
must be lowercase. It may include hyphens.
version: The initial value is 1.0.0. You update the number when you update your package using semantic
versioning.
description: You can provide a description of your package here. Indicate what your package does and how
to use it.
entry point: The entry file for your code. The default value is index.js.
test command: Here, you can add the command you want to run when a user runs npm run test.
git repository: The link to your remote repository on GitHub.
keywords: Add relevant keywords that will help others find your package on the NPM registry.
author: Add your name.
license: You can add a license or use the default license (Internet Systems Consortium (ISC) License
The node_modules directory is the folder where NPM places all the packages it
downloads locally for your project.

The package-lock.json file is a document NPM uses to record the exact version of all the
packages you've installed locally to your project's node_modules directory.

A package-lock.json file makes an app 100% reproducible in the exact way you published it
to the NPM registry.
Dependencie: Packages required by your application in production.
Dependency is an object that contains the library, which your project requires for production environments and
functioning effectively. You require these packages to test and run your project on the localhost.

To add dependencies to the package.json file by running the below command:

npm install <dependencies>

whenever a user installs your project from the NPM registry, the dependencies property ensures package managers
can automatically find and install the packages listed.

Note that you can add a package to the "dependencies" field through either of the following ways:

Manually add the name and the semantic version of each package your project depends on in production.

Run the npm install package-name --save-prod command on your terminal.


DevDependencies: Packages that are only needed for local development.
devDependencies are those packages in the package.json file that you need only for project development purposes.
Example- Babel, Webpack, etc.

These types of dependencies are required during the web application development process but not while testing or
executing it. Whenever you add a library or module that is required only in the development of your project, you can find
it under devDependencies
For adding devDependencies to your project, run the below command:

npm install <dev_dependencies> --save-dev


you can add a package to the "devDependencies" field through either of the following ways:

Manually add the name and the semantic version of each package on which your project depends for its development and
testing purposes.
Run the npm install package-name --save-dev command on your terminal. Or yarn add package-name --dev if Yarn is
your package manager.
"name": "dev_dependencies",
"version": "1.1.0",
"dependencies": {
"my_dep": "^1.1.0",
"another_dep": "~2.1.0"
},
"devDependencies" : {
"my_test_framework": "^3.2.0".
"another_dev_dep": "1.1.0 - 1.3.0"
}
Installing a Node Package
There are two ways to install a package: locally or globally.
Local package installation
A locally installed package is one that you can use only in the project in which you've installed it.
To install a package locally, do the following:
Navigate to the root directory of your project from the command line.
Install your package using the NPM installation command
npm install package-name --save
Note:- that the --save command above instructs NPM to save package-name in the package.json file as one of the packages on
which the project depends.

Global package installation


A globally installed package is a package that you can use anywhere on your system.
To install a package globally, run the code below on your terminal:
npm install package-name -g
Using npm packages in your projects
Once you have installed a package in node_modules, you can use it in your code.
Node.js module
If you are creating a Node.js module, you can use a package in your module by passing it as an argument to the
require function.

var lodash = require('lodash');


var output = lodash.without([1, 2, 3], 1);
console.log(output);
In package.json, list the package under dependencies. You can optionally include a semantic version.
{
"dependencies": {
"package_name": "^1.0.0"
}
}
Using scoped packages in your projects
To use a scoped package, simply include the scope wherever you use the package name.
var projectName = require("@scope/package-name")
In package.json:
{
"dependencies": {
"@scope/package_name": "^1.0.0"
}
}

Globally installed packages and their dependencies


npm list -g

Locally installed packages and their dependencies


npm list
Uninstalling a package
To uninstall a package from a specific project
First, navigate to the project's root directory from the command line and run:
npm uninstall package-name

To uninstall a global package


npm uninstall package-name -g
Publishing and updating a package to npm
NPM is a free registry for public package authors.
So, it is used to publish any project (folder) from your computer that has a package.json file.
Step 1: Create package
Then in terminal write the following commands
npm init
npm link
Step 2: Log in
Login to NPMJS account from the command line like so:
npm login
Enter username and password
Step 3: Publish your package!
Go to your project's root directory and publish it like so:
npm publish
Make sure that your package's name does not currently exist on NPM. Otherwise, you will get an error while publishing.
To Update npm and Packages
Keeping your npm and packages up to date is the single best way to keep bugs and security flaws away from your code.
To update npm to its latest version, use the command below:
npm install npm@latest - g
This updates npm globally on your computer.
When the creators of a package introduce new features or fix bugs, they update the package on the npm registry. You then
have to update your own package in order to make use of the new features.
Here is the syntax of the command you’d use to do this:
npm update [package name]
And here’s a working example:
npm update typescript
EXRESS JS
"Express is a fast, unopinionated minimalist web framework for Node.js“
- official web site: Expressjs.com
• Express js is a very popular web application framework built to create Node.js Web
based applications.
• It is a minimal and flexible framework that provides a set of features for web and
mobile application development.
• It provides an integrated environment to facilitate rapid development of Node based
Web applications.
• It provides us the tools that are required to build our app.
• It is flexible as there are numerous modules available on npm, which can be directly
plugged into Express.
• Express was developed by TJ Holowaychuk and is maintained by the Node.js
foundation and numerous open source contributors.
• Express framework is based on Connect middleware engine and used Jade html
template framework for HTML templating.
• It's a layer built on the top of the Node js that helps manage servers and routes.
• With ExpressJS, you need not worry about low level protocols, processes, Etc
Following is the list of some distinctive features of this framework:
• It can be used to design single-page, multi-page, and hybrid web applications and APIs.
• It allows to set up middleware to respond to HTTP/RESTful Requests.
• It defines a routing table to perform different HTTP operations (method and URL).
• It allows to dynamically rendering HTML Pages based on passing arguments to
templates.
• It provides high performance because of its ultra-fast I/O. It prepares a thin layer;
therefore, the performance is adequate.
• Its MVC-like structure makes it organize the web application into MVC architecture.
• It provides good database support. It supports RDBMS as well as NoSQL databases.
• It is asynchronous and single-threaded.
• Its robust API makes routing easy.
Life cycle of Express App

Initialization:

const express = require("express");


var app = express();

Middleware Execution:

app.use((req, res, next) => {


// Middleware logic
next(); // Call next to pass control to the next middleware in the stack
});

Routing:

app.get("/", (req, res) => {


res.send("Hello from my root ");
});
Route Handlers:

app.get('/profile/:username', (req, res) => {


const username = req.params.username;
res.send(`Profile for ${username}`);
});

Error Handling:

app.use((err, req, res, next) => {


// Error-handling logic
res.status(500).send('Internal Server
Error');
});

Response Sent:
app.get('/api/data', (req, res) => {
const data = { key: 'value' };
res.json(data);
});
Installation and the First Program
To install Express JS on your system first you need to install node js then we will write a command to install express in the
terminal.

• npm install express (local)

The express js will be installed in your system.

Example 1: hello world


const express =require('express')
const app =express()
const port =3000

app.get('/',(req, res)=>{
res.send('Hello World!')
})

app.listen(port,()=>{
console.log(`Example app listening on port ${port}`)
})
Routing refers to determining how an application responds to a client request to a
particular endpoint, which is a URI (or path) and a specific HTTP request method (GET,
POST, and so on).

Each route can have one or more handler functions, which are executed when the route is
matched.

Route definition takes the following structure:

app.METHOD(PATH, HANDLER)
Where:

app is an instance of express.


METHOD is an HTTP request method, in lowercase.
PATH is a path on the server.
HANDLER is the function executed when the route is matched.
The following code is an example of a very basic route.

const express = require('express')


const app = express()

// respond with "hello world" when a GET request is made to the homepage
app.get('/', (req, res) => {
res.send('hello world')
})
The request (req) and response (res) objects are fundamental components of handling HTTP requests and
generating HTTP responses. They come with various properties and methods that allow you to access and
manipulate different aspects of the HTTP transaction. Below are some of the commonly used properties and
methods of the req and res objects:

Request (req) Object:

1.params: Contains route parameters extracted from the URL


Ex:-
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
});

2.req.query: Contains the query parameters from the URL.


// For a URL like /search?q=keyword
const keyword = req.query.q;

3. req.body:Contains the parsed request body for POST and PUT requests.
app.post('/users', (req, res) => {
const userData = req.body;
});
4.req.headers:Contains the headers sent with the request.
const contentType = req.headers['content-type’];

5.req.cookies:Contains cookies sent by the client.


const userCookie = req.cookies.user;
// Requires middleware like cookie-parser

6.req.method:Contains the HTTP method of the request (GET, POST, PUT, DELETE, etc.).
const httpMethod = req.method;

Response (res) Object:

1.res.send():Sends a response to the client. It can be a string, object, buffer, or HTML.


res.send('Hello, World!');

2. Sends a JSON response to the client.


res.json({ message: 'Hello, JSON!' });
3.res.redirect():Redirects the client to a different URL.
res.redirect('/new-location’);

4.res.setHeader():Sets a single header value for the response.


res.setHeader('Content-Type', 'application/json’);

5.res.cookie():Sets a cookie in the client's browser.


res.cookie('user', 'john-doe’);

6. res.status():Sets the HTTP status code for the response.


res.status(404).send('Not Found');
Example:-
const express = require("express");
const app = express();

app.get("", (req, resp) => {


console.log(req.query);
// console.log(req.query.name);
// resp.send("Welcome," + req.query.name);
resp.send("Welcome, this is home page");
});
app.listen(5001);
Better Way to initialize configuration parameters.
Using a Configuration File:
Create a configuration file, such as config.js:

Config.js
module.exports = {
port: process.env.PORT || 3000
};

Index.js
const express = require('express');
const config = require('./config');
const app = express();

app.listen(config.port, () => {
console.log(`Server is running on port ${config.port}`);
});
A config file can also export separate variables that hold the values or a simple object with custom depth level
so we can also give scope to the config elements.This is far from perfect as every time we want to change a
config value, we have to touch the code. We can overcome this with the help of environment variables

In Node.js and Express.js, you can read configuration parameters from various sources, such as environment
variables, configuration files, command line arguments, or a combination of these. Here's a basic guide on how
you can achieve this:

Using Environment Variables:


Environment variables are a common way to configure applications. You can set them outside of your
application, making it easy to change configurations without modifying your code.
You can set environment variables as separate
file:
Config.env
NODE_ENV=development
PORT=3000
USERNAME = admin
PASSWORD = 123456
API_KEY=your_api_key
Index.js
const dotenv = require("dotenv");
dotenv.config({ path: "./config.env" });
const express = require("express");
const app = express();
console.log(process.env);
const port = process.env.PORT || 3000;
const apiKey = process.env.API_KEY;

app.listen(port, () => {
console.log("server has started...");
});

Terminal commands:- npm init,


Npm install express, npm install dotenv,npm start.

You might also like