node.js unit-4
node.js unit-4
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?
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
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.
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
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.
SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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.
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
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.
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.
To access NPM help, write npm help in the command prompt or terminal window.
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.
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.
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"
}
}
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
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);
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
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
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.
SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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');
});
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 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.
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
});
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
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');
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 == "/admin") {
}
else
res.end('Invalid Request!');
});
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
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
server.listen(5000);
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);
Node.js Events
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();
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.
// 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;
//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.
SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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 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();
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();
SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
res.send('<html><body><h1>Hello World</h1></body></html>');
});
SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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.
<!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.
SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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.
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.
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.)
app.js
Example
Create a database called "mydb":
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/MyDb";
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.
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
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
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
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/MyDb", function (err, db) {
});
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.
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":
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/";
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
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":
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
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
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.
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
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":
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
SUDHAKAR DWIVEDI,AP,IT,AKGEC
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
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/";
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:
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:
]).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
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.
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.
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. 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:
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.
SUDHAKAR DWIVEDI,AP,IT,AKGEC