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

node.js unit-4

Uploaded by

st250403
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
28 views41 pages

node.js unit-4

Uploaded by

st250403
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 41

Ajay Kumar Garg Engineering College, Ghaziabad

Information Technology Department

What is Node.js?

Node.js is an open-source server side runtime environment built on Chrome's V8 JavaScript engine.
It provides an event driven, non-blocking (asynchronous) I/O and cross-platform runtime environment
for building highly scalable server-side application using JavaScript.
Node.js can be used to build different types of applications such as command line application, web
application, real-time chat application, REST API server etc.
However, it is mainly used to build network programs like web servers, similar to PHP, Java, or
ASP.NET.
Node.js was written and introduced by Ryan Dahl in 2009 have following features :
• Node.js is an open source server environment
• Node.js is free
• Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
• Node.js uses JavaScript on the server

Why Node.js?

Node.js uses asynchronous programming!

Advantages of Node.js

1. Node.js is an open-source framework under MIT license. (MIT license is a free software license
originating at the Massachusetts Institute of Technology (MIT).)
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

Traditional Web Server Model

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

In the traditional web server model, each request is handled by a dedicated thread from the thread pool.
If no thread is available in the thread pool at any point of time then the request waits till the next
available thread. Dedicated thread executes a particular request and does not return to thread pool until
it completes the execution and returns a response.

Here is how PHP or ASP handles a file request:


1. Sends the task to the computer's file system.
2. Waits while the file system opens and reads the file.
3. Returns the content to the client.
4. Ready to handle the next request.

Node.js Process Model

Node.js processes user requests differently when compared to a traditional web server model. Node.js
runs in a single process and the application code runs in a single thread and thereby needs less resources
than other platforms. All the user requests to your web application will be handled by a single thread
and all the I/O work or long running job is performed asynchronously for a particular request. So, 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.
An event loop is constantly watching for the events to be raised for an asynchronous job and executing
callback function when the job completes. Internally, Node.js uses libev for the event loop which in
turn uses internal C++ thread pool to provide asynchronous I/O.
Here is how Node.js handles a file request:
SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

1. Sends the task to the computer's file system.


2. Ready to handle the next request.
3. When the file system has opened and read the file, the server returns the content to the client.
Node.js eliminates the waiting, and simply continues with the next request.
Node.js runs single-threaded, non-blocking, asynchronous programming, which is very memory
efficient.

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Node.js Console/REPL

Node.js comes with virtual environment called REPL (aka Node shell). REPL stands for Read-Eval-
Print-Loop. It is an interactive environment provided by Node.js to execute JavaScript code on the fly.
It is a quick and easy way to test simple Node.js/JavaScript code.
Starting the REPL:
To launch the REPL (Node shell), open command prompt (in Windows) or terminal (in Mac or
UNIX/Linux) and type node as shown below. It will change the prompt to > in Windows and MAC.

Node.js/JavaScript expression in REPL. 10 + 20 will display 30 immediately in new line.


The + operator also concatenates strings as in browser's JavaScript.
For multi-line JavaScript expression or function then just press Enter whenever you want to write
something in the next line as a continuation of your code.
The REPL terminal will display three dots (...), it means you can continue on next line.
Write. break to get out of continuity mode.

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Executing External JavaScript File

We can execute an external JavaScript file by executing the node filename command.
To run your application, open a terminal, navigate to the directory containing app.js, and execute:
For example, the following runs mynodejs-app.js on the command prompt/terminal and displays the
result.
console.log("Hello World");

To exit from the REPL terminal, press Ctrl + C twice or write .exit and press Enter.

Online REPL Terminal

Several online platforms offer REPL environments for running Node.js code without any installation:
• repl.it: https://replit.com/
• JSFiddle: https://jsfiddle.net/
• CodeSandbox: https://codesandbox.io/
The following are the 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.

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

.break Exit from multiline expression.


.clear Exit from multiline expression.

NPM - Node Package Manager

Node Package Manager (NPM) is a 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.
The node community around the world creates useful modules and publishes them as packages in this
repository.
It has now become a popular package manager for other open-source JavaScript frameworks like
AngularJS, jQuery, Gulp, Bower etc.
NPM is included with Node.js installation.

To install a module using npm, we can use the following command:


npm install <module>
For Ex: npm install express

After we install Node.js, verify NPM installation by writing the following command in terminal or
command prompt.

C:\> npm -v
2.11.3

If you have an older version of NPM then you can update it to the latest version using the following
command.

C:\> npm install npm -g

To access NPM help, write npm help in the command prompt or terminal window.

C:\> npm help

NPM performs the operation in two modes:


1. global mode
2. local mode
Global Mode : In the global mode, NPM performs operations which affect all the Node.js
applications on the computer

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Local Mode :In the local mode, NPM performs operations for the particular local directory which
affects an application in that directory only.

Install Package Locally

Use the following command to install any third-party module in our local Node.js project folder.
C:\>npm install <package name>
For example, the following command will install ExpressJS into MyNodeProj folder.
C:\MyNodeProj> npm install express
All the modules installed using NPM are installed under node_modules folder.
The above command will create ExpressJS folder under node_modules folder in the root folder of your
project and install Express.js there.

Attributes of package.json

Package.json is a file that holds various metadata relevant to the project and is used to manage the
project's dependencies, scripts, version, and other settings.
Common attributes include:
• name: The name of your project.
• version: The version of your project.
• description: A brief description of your project.
• main: The entry point of your application.
• scripts: Scripts that can be run with npm run <script-name>.
• dependencies: A list of dependencies required by your project.
• devDependencies: A list of dependencies required only for development.
• author: The author of the project.
• license: The license under which the project is released.

Add Dependency into package. Json

Use --save at the end of the install command to add dependency entry into package.json of our
application.
For example, the following command will install ExpressJS in our application and also adds
dependency entry into the package.json.
C:\MyNodeProj> npm install express --save
The package.json of NodejsConsoleApp project will look something like below.
package.json

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Copy
{
"name": "NodejsConsoleApp",
"version": "0.0.0",
"description": "NodejsConsoleApp",
"main": "app.js",
"author": {
"name": "Dev",
"email": ""
},
"dependencies": {
"express": "^4.13.3"
}
}

Install Package Globally

NPM can also install packages globally so that all the node.js application on that computer can import
and use the installed packages. NPM installs global packages
into /<User>/local/lib/node_modules folder.
Apply -g in the install command to install package globally. For example, the following command will
install ExpressJS globally.
C:\MyNodeProj> npm install -g express

Update Package

To update the package installed locally in our Node.js project, navigate the command prompt or
terminal window path to the project folder and write the following update command.
C:\MyNodeProj> npm update <package name>
The following command will update the existing ExpressJS module to the latest version.
C:\MyNodeProj> npm update express

Uninstall Packages

Use the following command to remove a local package from your project.

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

C:\>npm uninstall <package name>


The following command will uninstall ExpressJS from the application.
C:\MyNodeProj> npm uninstall express

Node.js Modules

It same as JavaScript libraries. A set of functions you want to include in our application.

Built-in Modules

Node.js has a set of built-in modules which we can use without any further installation.
To include a module, use the require() function with the name of the module:
var http = require('http');
Now our application has access to the HTTP module, and is able to create a server:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);

Create Your Own Modules

We can create our own modules, and easily include them in our applications.
The following example creates a module that returns a date and time object:
Create a module that returns the current date and time:
exports.myDateTime = function ()
{
return Date();
};
Use the exports keyword to make properties and methods available outside the module file.
Save the code above in a file called "myfirstmodule.js"
Include Your Own Module
Now we can include and use the module in any of our Node.js files.
var http = require('http');
var dt = require('./myfirstmodule');
SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time are currently: " + dt.myDateTime());
res.end();
}).listen(8080);

We use ./ to locate the module, that means that the module is located in the same folder as the Node.js
file.
Save the code above in a file called "demo_module.js", and initiate the file:
Initiate demo_module.js:
C:\Users\Your Name>node demo_module.js

Callback Concept: What is a Callback

A callback is a function passed into another function as an argument, which is then invoked inside the
outer function to complete some kind of routine or action.
It is a way to handle asynchronous tasks in JavaScript, allowing operations like reading files, making
HTTP requests, or querying databases to avoid blocking the main execution thread.

Example: File Reading with Callback


const fs = require('fs');
// Asynchronous file read with callback
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading the file:', err);
return;
}
console.log('File content:', data);
});

console.log('Reading file...'); // This will execute before the file is read.

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Explanation of the Example:


1. fs.readFile: This is a Node.js asynchronous method to read a file.
2. Callback Function: The function (err, data) is passed as a parameter to fs.readFile.
o err: Captures any errors during the file reading process.
o data: Contains the content of the file if the operation is successful.
3. Non-blocking Behavior: The console.log('Reading file...') line executes before the file reading
operation completes because fs.readFile runs asynchronously.

How Node.js Applications Work

Node.js applications are built on an event-driven, non-blocking I/O model. This architecture enables
Node.js to handle many simultaneous connections efficiently, making it ideal for I/O-intensive tasks
such as web servers, APIs, and real-time applications.
Lifecycle of a Node.js Application
1. Initialization: Node.js initializes the program, runs any synchronous code, and sets up the
environment.
2. Event Registration: The application registers event handlers for different events.
3. Event Loop Execution: The event loop starts, processing events and executing corresponding
event handlers.

Example Application

Step-by-Step Example
1. Import Required Modules
First, we need to import the built-in http module:
const http = require('http');
2. Create the Server
We create an HTTP server using the http.createServer() method. This method takes a callback function
that will be executed whenever an HTTP request is received.
const server = http.createServer((req, res) => {
res.statusCode = 200; // Set the response status code to 200 (OK)
res.setHeader('Content-Type', 'text/plain'); // Set the response content type
res.end('Hello, World!\n'); // Send the response and close the connection
SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

});
3. Listen on a Port
We make the server listen on a specific port (e.g., 3000) and hostname (e.g., '127.0.0.1').
const port = 3000;
const hostname = '127.0.0.1';
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Full Example
Here's the complete code for the simple HTTP server:
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!\n');
});

server.listen(port, hostname, () => {


console.log(`Server running at http://${hostname}:${port}/`);
});
Detailed Explanation
• Importing Modules: const http = require('http'); imports the built-in HTTP module.
• Creating the Server: http.createServer((req, res) => {...}); creates an HTTP server. The
callback function handles incoming requests.
o res.statusCode = 200; sets the HTTP status code to 200 (OK).
o res.setHeader('Content-Type', 'text/plain'); sets the response content type to plain text.
o res.end('Hello, World!\n'); sends the response body and ends the response.

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

• Listening on a Port: server.listen(port, hostname, () => {...}); makes the server listen on the
specified port and hostname.
o The callback function logs a message when the server starts listening.

Node.js HTTP Module

The Built-in HTTP Module


Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text
Transfer Protocol (HTTP).
To include the HTTP module, use the require () method:
var http = require('http');

Node.js Web Server

Node.js provides capabilities to create our own web server which will handle HTTP requests
asynchronously.
We can use IIS or Apache to run Node.js web application but it is recommended to use Node.js web
server.

Create Node.js Web Server

Node.js makes it easy to create a simple web server that processes incoming requests asynchronously.
The following example is a simple Node.js web server contained in server.js file.
var http = require('http'); // 1 - Import Node.js core module

var server = http.createServer(function (req, res) { // 2 - creating server

//handle incomming requests here..

});

server.listen(5000); //3 - listen for any incoming requests

console.log('Node.js web server at port 5000 is running..')

Run the above web server by writing node server.js command in command prompt or terminal window
and it will display message as shown below.

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

C:\> node server.js

Node.js web server at port 5000 is running..

Node.js as a Web Server

The HTTP module can create an HTTP server that listens to server ports and gives a response back to
the client.
Use the createServer() method to create an HTTP server:
var http = require('http');

//create a server object:


http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080

Handle HTTP Request

The http.createServer() method includes request and response parameters which is supplied by
Node.js. The request object can be used to get information about the current HTTP request e.g., url,
request header, and data. The response object can be used to send a response for a current HTTP
request.
The following example demonstrates handling HTTP request and response in Node.js.
server.js
var http = require('http'); // Import Node.js core module
var server = http.createServer(function (req, res) { //create web server
if (req.url == '/') { //check the URL of the current reques
// set response header
res.writeHead(200, { 'Content-Type': 'text/html' });
// set response content
res.write('<html><body><p>This is home Page.</p></body></html>');
res.end();
}

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

else if (req.url == "/student") {


res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<html><body><p>This is student Page.</p></body></html>');
res.end();

}
else if (req.url == "/admin") {

res.writeHead(200, { 'Content-Type': 'text/html' });


res.write('<html><body><p>This is admin Page.</p></body></html>');
res.end();

}
else
res.end('Invalid Request!');

});

server.listen(5000); //6 - listen for any incoming requests

console.log('Node.js web server at port 5000 is running..')


In the above example, req.url is used to check the url of the current request and based on that it sends
the response.
To send a response, first it sets the response header using writeHead() method and then writes a string
as a response body using write() method.
Finally, Node.js web server sends the response using end() method.

Now, run the above web server as shown below.


C:\> node server.js
Node.js web server at port 5000 is running..

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

To test it, you can use the command-line program curl, which most Mac and Linux machines have
pre-installed.

curl -i http://localhost:5000

We should see the following response.


HTTP/1.1 200 OK
Content-Type: text/plain
Date: Tue, 8 Sep 2015 03:05:08 GMT
Connection: keep-alive
This is home page.

For Windows users, point your browser to http://localhost:5000 and see the following result.

The same way, point your browser to http://localhost:5000/student and see the following result.

It will display "Invalid Request" for all requests other than the above URLs.
SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Sending JSON Response


The following example demonstrates how to serve JSON response from the Node.js web server.
server.js
var http = require('http');
var server = http.createServer(function (req, res) {
if (req.url == '/data') { //check the URL of the current request
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify({ message: "Hello World"}));
res.end();
}
});

server.listen(5000);

console.log('Node.js web server at port 5000 is running..')


It will display "Invalid Request" for all requests other than the above URLs.

Sending JSON Response

The following example demonstrates how to serve JSON response from the Node.js web server.
server.js
var http = require('http');
var server = http.createServer(function (req, res) {
if (req.url == '/data') { //check the URL of the current request
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify({ message: "Hello World"}));
res.end();
}
});

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

server.listen(5000);

console.log('Node.js web server at port 5000 is running..')


So, this way we can create a simple web server that serves different responses.

Node.js Events

Node.js is perfect for event-driven applications.


Events in Node.js
Every action on a computer is an event. Like when a connection is made or a file is opened.
Objects in Node.js can fire events, like the readStream object fires events when opening and closing
a file:
Example
var fs = require('fs');
var rs = fs.createReadStream('./demofile.txt');
rs.on('open', function ()
{
console.log('The file is open');
});

Events Module

Node.js has a built-in module, called "Events", where we can create-, fire-, and listen for- our own
events.
To include the built-in Events module use the require() method. In addition, all event properties and
methods are an instance of an EventEmitter object.
To be able to access these properties and methods, create an EventEmitter object:
var events = require('events');
var eventEmitter = new events.EventEmitter();

The EventEmitter Object

We can assign event handlers to our own events with the EventEmitter object.

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

The following example demonstrates EventEmitter class for raising and handling a custom event.

Example: Raise and Handle Node.js events

// get the reference of EventEmitter class of events module


var events = require('events');

//create an object of EventEmitter class by using above reference


var em = new events.EventEmitter();

//Subscribe for FirstEvent


em.on('FirstEvent', function (data) {
console.log('First subscriber: ' + data);
});

// Raising FirstEvent
em.emit('FirstEvent', 'This is my first Node.js event emitter example.');

We first import the 'events' module and then create an object of EventEmitter class.
We then specify event handler function using on() function. The on() method requires name of the
event to handle and callback function which is called when an event is raised.
The emit() function raises the specified event. First parameter is name of the event as a string and then
arguments. An event can be emitted with zero or more arguments. You can specify any name for a
custom event in the emit() function.
We can also use addListener() methods to subscribe for an event as shown below.

Example: EventEmitter
var emitter = require('events').EventEmitter;

var em = new emitter();

//Subscribe FirstEvent
em.addListener('FirstEvent', function (data) {
console.log('First subscriber: ' + data);
});

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

//Subscribe SecondEvent
em.on('SecondEvent', function (data) {
console.log('First subscriber: ' + data);
});

// Raising FirstEvent
em.emit('FirstEvent', 'This is my first Node.js event emitter example.');

// Raising SecondEvent
em.emit('SecondEvent', 'This is my second Node.js event emitter example.');

The following table lists all the important methods of EventEmitter class.

EventEmitter Methods Description


emitter.addListener(event, listener) Adds a listener to the end of the listeners array for
the specified event. No checks are made to see if
the listener has already been added.
emitter.on(event, listener) Adds a listener to the end of the listeners array for
the specified event. No checks are made to see if
the listener has already been added. It can also be
called as an alias of emitter.addListener()
emitter.once(event, listener) Adds a one time listener for the event. This listener
is invoked only the next time the event is fired, after
which it is removed.
emitter.removeListener(event, Removes a listener from the listener array for the
listener) specified event. Caution: changes array indices in
the listener array behind the listener.
emitter.removeAllListeners([event]) Removes all listeners, or those of the specified
event.
emitter.setMaxListeners(n) By default EventEmitters will print a warning if
more than 10 listeners are added for a particular
event.

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

emitter.getMaxListeners() Returns the current maximum listener value for the


emitter which is either set by
emitter.setMaxListeners(n) or defaults to
EventEmitter.defaultMaxListeners.
emitter.listeners(event) Returns a copy of the array of listeners for the
specified event.
emitter.emit(event[, arg1][, arg2][, Raise the specified events with the supplied
...]) arguments.
emitter.listenerCount(type) Returns the number of listeners listening to the type
of event.

Frameworks for Node.js

We need to write lots of low level code ourselves to create a web application using Node.js in Node.js
web server section.
There are various third party open-source frameworks available in Node Package Manager which
makes Node.js application development faster and easy.
We can choose an appropriate framework as per our application requirements.
The following table lists frameworks for Node.js.
Top 10 Node.js frameworks for app development
1. Express.js
2. Koa.js
3. Meteor.js
4. Nest.js
5. Hapi.js
6. Sails.js
7. Adonis.js
8. LoopBack
9. Total.js
10. Restify

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Express.js

"Express is a fast, unopinionated minimalist web framework for Node.js" - official web
site: Expressjs.com
Express.js is a web application framework for Node.js. It 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
1. Makes Node.js web application development fast and easy.
2. Easy to configure and customize.
3. Allows you to define routes of your application based on HTTP methods and URLs.
4. Includes various middleware modules which you can use to perform additional tasks on
request and response.
5. Easy to integrate with different template engines like Jade, Vash, EJS etc.
6. Allows you to define an error handling middleware.
7. Easy to serve static files and resources of your application.
8. Allows you to create REST API server.
9. Easy to connect with databases such as MongoDB, Redis, MySQL

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Express.js Web Application

Express.js provides an easy way to create web server and render HTML pages for different HTTP
requests by configuring routes for your application.
Web Server
First of all, import the Express.js module and create the web server as shown below.
app.js: Express.js Web Server
var express = require('express');
var app = express();

// define routes here..

var server = app.listen(5000, function () {


console.log('Node server is running..');
});

The app.listen() function creates the Node.js web server at the specified host and port. It is identical to
Node's http.Server.listen() method.
Run the above example using node app.js command and point your browser to http://localhost:5000.
It will display Cannot GET / because we have not configured any routes yet.

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.
Example: Configure Routes in Express.js
var express = require('express');
var app = express();

app.get('/', function (req, res) {

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

res.send('<html><body><h1>Hello World</h1></body></html>');
});

app.post('/submit-data', function (req, res) {


res.send('POST Request');
});

app.put('/update-data', function (req, res) {


res.send('PUT Request');
});

app.delete('/delete-data', function (req, res) {


res.send('DELETE Request');
});

var server = app.listen(5000, function () {


console.log('Node server is running..');
});
app.get(), app.post(), app.put() and app.delete() methods define routes for HTTP GET, POST, PUT,
DELETE respectively. The first parameter is a path of a route which will start after base URL. The
callback function includes request and response object which will be executed on each request.
Run the above example using node server.js command, and point your browser
to http://localhost:5000 and you will see the following result.

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Handle POST Request

How to handle HTTP POST request and get data from the submitted form.
First, create Index.html file in the root folder of your application and write the following HTML code
in it.

Example: Configure Routes in Express.js

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<meta property="og:title" content="" />
</head>

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

<body>
<form action="/submit-student-data" method="post">
First Name: <input name="firstName" type="text" /> <br />
Last Name: <input name="lastName" type="text" /> <br />
<input type="submit" />
</form>
</body>
</html>

Body Parser

To handle HTTP POST request in Express.js version 4 and above, we need to install middleware
module called body-parser.
The middleware was a part of Express.js earlier but now we have to install it separately.
This body-parser module parses the JSON, buffer, string and url encoded data submitted using HTTP
POST request. Install body-parser using NPM as shown below.
npm install body-parser --save
Now, import body-parser and get the POST request data as shown below.

app.js: Handle POST Route in Express.js


var express = require('express');
var app = express();

var bodyParser = require("body-parser");


app.use(bodyParser.urlencoded({ extended: false }));

app.get('/', function (req, res) {


res.sendFile('index.html');
});

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

app.post('/submit-student-data', function (req, res) {


var name = req.body.firstName + ' ' + req.body.lastName;

res.send(name + ' Submitted Successfully!');


});

var server = app.listen(5000, function () {


console.log('Node server is running..');
});
POST data can be accessed using req.body. The req.body is an object that includes properties for each
submitted form. Index.html contains firstName and lastName input types, so you can access it using
req.body.firstName and req.body.lastName.
Now, run the above example using node server.js command, point your browser
to http://localhost:5000 and see the following result.

Data Access in Node.js

Node.js supports all kinds of databases no matter if it is a relational database or NoSQL database.
However, NoSQL databases like MongoDb are the best fit with Node.js.

Access MongoDB in Node.js

In order to access MongoDB database, we need to install MongoDB drivers.

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

To install native mongodb drivers using NPM, open command prompt and write the following
command to install MongoDB driver in your application.

npm install mongodb --save

This will include mongodb folder inside node_modules folder. Now, start the MongoDB server using
the following command. (Assuming that your MongoDB database is at
C:\MyNodeJSConsoleApp\MyMongoDB folder.)

mongod -dbpath C:\MyNodeJSConsoleApp\MyMongoDB

Connecting / Creating MongoDB

The following example demonstrates connecting to the local MongoDB database.


To create a database in MongoDB, start by creating a MongoClient object, then specify a connection
URL with the correct ip address and the name of the database you want to create.
MongoDB will create the database if it does not exist, and make a connection to it

app.js
Example
Create a database called "mydb":
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/MyDb";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
console.log("Database created!");
db.close();
});

we have imported mongodb module (native drivers) and got the reference of MongoClient object.
Then we used MongoClient.connect() method to get the reference of specified MongoDB database.
The specified URL "mongodb://localhost:27017/MyDb" points to your local MongoDB database
created in MyMongoDB folder.
The connect() method returns the database reference if the specified database is already exists,
otherwise it creates a new database.

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Save the code above in a file called "demo_create_mongo_db.js" and run the file:
Run "demo_create_mongo_db.js"
C:\Users\Your Name>node demo_create_mongo_db.js
Which will give you this result:
Database created!

Now you can write insert/update or query the MongoDB database in the callback function of the
connect() method using db parameter.

Node.js MongoDB Create Collection

A collection in MongoDB is the same as a table in MySQL.


Creating a Collection
To create a collection in MongoDB, use the createCollection() method:
ExampleGet your own Node.js Server
Create a collection called "customers":
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
dbo.createCollection("customers", function(err, res) {
if (err) throw err;
console.log("Collection created!");
db.close();
});
});

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Save the code above in a file called "demo_mongodb_createcollection.js" and run the file:
Run "demo_mongodb_createcollection.js"
C:\Users\Your Name>node demo_mongodb_createcollection.js
Which will give you this result:
Collection created!

Insert Documents
The following example demonstrates inserting documents into MongoDB database.

Example -1

Insert a document in the "customers" collection:

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
var myobj = { name: "Company Inc", address: "Highway 37" };
dbo.collection("customers").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});
});

Save the code above in a file called "demo_mongodb_insert.js" and run the file:
Run "demo_mongodb_insert.js"
C:\Users\Your Name>node demo_mongodb_insert.js
Which will give you this result:
1 document inserted

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Insert Multiple Documents


To insert multiple documents into a collection in MongoDB, we use the insertMany() method.
The first parameter of the insertMany() method is an array of objects, containing the data you want to
insert.
It also takes a callback function where you can work with any errors, or the result of the insertion:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
var myobj = [
{ name: 'John', address: 'Highway 71'},
{ name: 'Peter', address: 'Lowstreet 4'},
{ name: 'Amy', address: 'Apple st 652'},
{ name: 'Hannah', address: 'Mountain 21'},
{ name: 'Michael', address: 'Valley 345'},
{ name: 'Sandy', address: 'Ocean blvd 2'},
{ name: 'Betty', address: 'Green Grass 1'},
{ name: 'Richard', address: 'Sky st 331'},
{ name: 'Susan', address: 'One way 98'},
{ name: 'Vicky', address: 'Yellow Garden 2'},
{ name: 'Ben', address: 'Park Lane 38'},
{ name: 'William', address: 'Central st 954'},
{ name: 'Chuck', address: 'Main Road 989'},
{ name: 'Viola', address: 'Sideway 1633'}
];
dbo.collection("customers").insertMany(myobj, function(err, res) {
if (err) throw err;
console.log("Number of documents inserted: " + res.insertedCount);
db.close();
});
});

Save the code above in a file called "demo_mongodb_insert_multiple.js" and run the file:
Run "demo_mongodb_insert_multiple.js"
C:\Users\Your Name>node demo_mongodb_insert_multiple.js
Which will give you this result:
Number of documents inserted: 14

app.js
SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

var MongoClient = require('mongodb').MongoClient;

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/MyDb", function (err, db) {

db.collection('Persons', function (err, collection) {

collection.insert({ id: 1, firstName: 'Steve', lastName: 'Jobs' });


collection.insert({ id: 2, firstName: 'Bill', lastName: 'Gates' });
collection.insert({ id: 3, firstName: 'James', lastName: 'Bond' });

db.collection('Persons').count(function (err, count) {


if (err) throw err;

console.log('Total Rows: ' + count);


});
});

});

db.collection() method creates or gets the reference of the specified collection. Collection is similar to
table in relational database. We created a collection called Persons in the above example and insert
three documents (rows) in it. After that, we display the count of total documents stored in the collection.
Running the above example displays the following result.

> node app.js


Total Rows: 3

Update/Delete Documents
To delete a record, or document as it is called in MongoDB, we use the deleteOne() method.
The first parameter of the deleteOne() method is a query object defining which document to delete.
Delete the document with the address "Mountain 21":

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
var myquery = { address: 'Mountain 21' };
dbo.collection("customers").deleteOne(myquery, function(err, obj) {
SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

if (err) throw err;


console.log("1 document deleted");
db.close();
});
});

Save the code above in a file called "demo_delete.js" and run the file:
Run "demo_delete.js"
C:\Users\Your Name>node demo_delete.js
Which will give you this result:
1 document deleted

Delete Many
To delete more than one document, use the deleteMany() method.
The first parameter of the deleteMany() method is a query object defining which documents to delete.
Example
Delete all documents were the address starts with the letter "O":
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
var myquery = { address: /^O/ };
dbo.collection("customers").deleteMany(myquery, function(err, obj) {
if (err) throw err;
console.log(obj.result.n + " document(s) deleted");
db.close();
});

Save the code above in a file called "demo_delete_many.js" and run the file:
Run "demo_delete_many.js"
C:\Users\Your Name>node demo_delete_many.js
Which will give you this result:
2 document(s) deleted

Node.js MongoDB Update

Update Document
You can update a record, or document as it is called in MongoDB, by using the updateOne() method.
The first parameter of the updateOne() method is a query object defining which document to update.
Note: If the query finds more than one record, only the first occurrence is updated.
SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

The second parameter is an object defining the new values of the document.

Update the document with the address "Valley 345" to name="Mickey" and address="Canyon
123":

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://127.0.0.1:27017/";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
var myquery = { address: "Valley 345" };
var newvalues = { $set: {name: "Mickey", address: "Canyon 123" } };
dbo.collection("customers").updateOne(myquery, newvalues, function(err, res) {
if (err) throw err;
console.log("1 document updated");
db.close();
});
});

Save the code above in a file called "demo_update_one.js" and run the file:
Run "demo_update_one.js"
C:\Users\Your Name>node demo_update_one.js
Which will give you this result:
1 document updated

Update Only Specific Fields


When using the $set operator, only the specified fields are updated:
Example
Update the address from "Valley 345" to "Canyon 123":
...
var myquery = { address: "Valley 345" };
var newvalues = { $set: { address: "Canyon 123" } };
dbo.collection("customers").updateOne(myquery, newvalues, function(err, res) {
...

Update Many Documents


To update all documents that meets the criteria of the query, use the updateMany() method.

Example
Update all documents where the name starts with the letter "S":

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://127.0.0.1:27017/";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
var myquery = { address: /^S/ };
var newvalues = {$set: {name: "Minnie"} };
dbo.collection("customers").updateMany(myquery, newvalues, function(err, res) {
if (err) throw err;
console.log(res.result.nModified + " document(s) updated");
db.close();
});
});

save the code above in a file called "demo_update_many.js" and run the file:
Run "demo_update_many.js"
C:\Users\Your Name>node demo_update_many.js
Which will give you this result:
2 document(s) updated

Query Database
Filter the Result
When finding documents in a collection, you can filter the result by using a query object.
The first argument of the find() method is a query object, and is used to limit the search.

Find documents with the address "Park Lane 38":

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
var query = { address: "Park Lane 38" };
dbo.collection("customers").find(query).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Save the code above in a file called "demo_mongodb_query.js" and run the file:
Run "demo_mongodb_query.js"
C:\Users\Your Name>node demo_mongodb_query.js

Filter With Regular Expressions


We can write regular expressions to find exactly what we are searching for.

Regular expressions can only be used to query strings.

To find only the documents where the "address" field starts with the letter "S", use the regular
expression /^S/:

Example
Find documents where the address starts with the letter "S":

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
var query = { address: /^S/ };
dbo.collection("customers").find(query).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});

Save the code above in a file called "demo_mongodb_query_s.js" and run the file:
Run "demo_mongodb_query_s.js"
C:\Users\Your Name>node demo_mongodb_query_s.js

Node.js MongoDB Sort

Sort the Result


Use the sort() method to sort the result in ascending or descending order.
The sort() method takes one parameter, an object defining the sorting order.

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Sort the result alphabetically by name:

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
var mysort = { name: 1 };
dbo.collection("customers").find().sort(mysort).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});

Save the code above in a file called "demo_sort.js" and run the file:
Run "demo_sort.js"
C:\Users\Your Name>node demo_sort.js

Sort Descending
Use the value -1 in the sort object to sort descending.

{ name: 1 } // ascending
{ name: -1 } // descending

Example:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
var mysort = { name: -1 };
dbo.collection("customers").find().sort(mysort).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Save the code above in a file called "demo_sort_desc.js" and run the file:
Run "demo_sort_desc.js"
C:\Users\Your Name>node demo_sort_desc.js
Which will give you this result:

Node.js MongoDB Join

Join Collections
MongoDB is not a relational database, but you can perform a left outer join by using the $lookup stage.
The $lookup stage lets you specify which collection you want to join with the current collection, and
which fields that should match.
Consider you have a "orders" collection and a "products" collection:

orders
[
{ _id: 1, product_id: 154, status: 1 }
]

products
[
{ _id: 154, name: 'Chocolate Heaven' },
{ _id: 155, name: 'Tasty Lemons' },
{ _id: 156, name: 'Vanilla Dreams' }
]

Example
Join the matching "products" document(s) to the "orders" collection:

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://127.0.0.1:27017/";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
dbo.collection('orders').aggregate([
{ $lookup:
{
from: 'products',
localField: 'product_id',
foreignField: '_id',
as: 'orderdetails'
}
}
SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

]).toArray(function(err, res) {
if (err) throw err;
console.log(JSON.stringify(res));
db.close();
});
});

Save the code above in a file called "demo_mongodb_join.js" and run the file:
Run "demo_mongodb_join.js"
C:\Users\Your Name>node demo_mongodb_join.js

What is the REST API?


Representational State Transfer Application Programming Interface is referred to as REST API. It
is an architectural style used to design networked applications, especially ones that use HTTP to
communicate with web-based services. The client and server interact with a REST API using common
HTTP methods like GET, POST, PUT, and DELETE.

Modern microservice designs frequently use REST APIs because they allow functionality to be divided
into small and independent services. As a result, the system as a whole is more flexible and
maintainable since each service can be developed, implemented, and scaled independently.

REST has become an accepted standard for developing APIs because it provides a simple-to-use,
scalable, and effective method of interacting with server-side services without being dependent on any
particular server technology.

What is a RESTful API?

The term "RESTful API" describes an API (application programming interface) that follows precisely
the architectural principles of Representational State Transfer (REST). It defines a set of
conventions for creating web services that communicate with resources (data) through the Internet and
use common HTTP methods like GET, POST, PUT, and DELETE.

With a RESTful API, applications can communicate with one another through HTTP requests and
responses without requiring an understanding of the internal workings of the service they are using.
Defined endpoints (URLs) serve as the base for the interaction, which follows REST principles
including statelessness, resource identification through URIs, and data representation using standard
formats like XML or JSON.

RESTful APIs are common for accessing and modifying data from a variety of web-connected
applications, databases, and services. By utilizing the ease of execution and efficacy of the HTTP
SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

protocol, they are suitable for developing unique software applications that are scalable, flexible,
and easy to maintain.

What are the main elements of RESTful API?

1. Resources: These are the primary objects or entities that the API makes available for use. A
"customer" or an "order" are examples of how each resource represents data. Clients can
understand and manipulate resources because they are frequently organized according to the
data they represent.
2. URIs (Uniform Resource Identifiers): URIs, or uniform resource identifiers, are similar to
addresses in that they serve as a unique means of identifying each given resource. For example,
an individual customer with the ID 1234 is recognized using the URI
https://api.example.com/customers/1234. Because it allows clients to recognize and access
specific resources, the URI structure is crucial.
3. HTTP Methods: RESTful APIs manipulate resources using the normal HTTP methods. These
include:

1. GET: Get a list of resources or a resource directly.


2. POST: Create a new resource.
3. PUT: Completely update a resource that already exists.
4. PATCH: Update a resource partially with a patch.
5. DELETE: Remove a resource.
4. Representations: A RESTful API's resources can be found in XML or JSON formats, among
others. Because of these formats, clients may read and use the data. By using the Accept header
in their requests, clients can tell the server what format they want to receive the data in, and the
server will react accordingly.
5. HTTP Status Codes: These codes provide the client with how their request was received.
Common status codes include:

1. 200 OK: The data requested by the user was successfully sent to the server.
2. 201 Created: The server successfully created a resource.
3. 400 Bad Request: The request was not valid or the server was unable to process it.
4. 404 Not Found: The server was unable to locate the requested resource.
6. Headers: HTTP headers in both requests and replies carry important metadata. For example:

1. Authorization: It contains the client's authentication credentials.


2. Content-Type: It indicates the resource's media type, such as application/json, that is
being sent.
3. Cache-Control: It provides directives for caching mechanisms.
7. Hypermedia: Clients can find relevant information or actions they can take by clicking on
hypermedia links within answers in RESTful APIs. For example, a response might provide
links to obtain specific client information, update customer data, or remove a customer after a

SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

list of customers has been provided. "Hypermedia As The Engine Of Application State", or
HATEOAS, is the term for this RESTful feature.
8. Statelessness: RESTful APIs are made to be stateless, which means that every request made
by the client to the server must contain all of the data required for the server to understand and
deal with the request. To ensure that each request may be handled separately and to simplify
server design, the server does not save any client session data between requests. The client
must maintain the session state.

Working:

Idempotence: An idempotent HTTP method is a HTTP method that can be called many times without
different outcomes. It would not matter if the method is called only once, or ten times over. The result
should be the same. Again, this only applies to the result, not the resource itself.

Example:
1. a = 4 // It is Idempotence, as final value(a = 4)
// would not change after executing it multiple
// times.

2. a++ // It is not Idempotence because the final value


// will depend upon the number of times the
// statement is executed.

SUDHAKAR DWIVEDI,AP,IT,AKGEC

You might also like