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

wt unit4 part 2

Uploaded by

khushisingh7628
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

wt unit4 part 2

Uploaded by

khushisingh7628
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Node.

js
Node.js is an open-source, cross-platform JavaScript runtime environment
that allows developers to run JavaScript code outside of a web browser:
 What it does
Node.js is used to create server-side web applications, such as traditional websites
and back-end API services. It's also used for data-intensive applications, real-time
web applications, and hardware programming

Node.js REPL
The term REPL stands for Read Eval Print and Loop. It specifies a computer environment like a
window console or a Unix/Linux shell where you can enter the commands and the system
responds with an output in an interactive mode.

REPL Environment
The Node.js or node come bundled with REPL environment. Each part of the REPL environment
has a specific work.

Read: It reads user's input; parse the input into JavaScript data-structure and stores in memory.

Eval: It takes and evaluates the data structure.

Print: It prints the result.

Loop: It loops the above command until user press ctrl-c twice.

Node.js REPL Commands


Commands Description

ctrl + c It is used to terminate the current command.

ctrl + c twice It terminates the node repl.

ctrl + d It terminates the node repl.

It is used to see command history and modify


up/down keys
previous commands.
How to start REPL
You can start REPL by simply running "node" on the command prompt. See this:

You can execute various mathematical operations on REPL Node.js command prompt:

Node.js Simple expressions


After starting REPL node command prompt put any mathematical expression:

1. Example: >10+20-5
2. 25
1. Example2: >10+12 + (5*4)/7

Node Package Manager(NPM): NPM (Node Package Manager) is a


package manager for Node.js modules. It helps developers manage
project dependencies, scripts, and third-party libraries. By installing
Node.js on your system, NPM is automatically installed, and ready to use.
 It is primarily used to manage packages or modules—these are pre-
built pieces of code that extend the functionality of your Node.js
application.
 The NPM registry hosts millions of free packages that you can
download and use in your project.
 NPM is installed automatically when you install Node.js, so you don’t
need to set it up manually.
To master NPM and streamline your full-stack development workflow,
the Full Stack Development with Node JS course offers detailed
lessons on managing packages, scripts, and dependencies for full-stack
applications
How to Use NPM with Node.js?
To start using NPM in your project, follow these simple steps
Step 1: Install Node.js and NPM
First, you need to install Node.js. NPM is bundled with the Node.js
installation.
Step 2: Verify the Installation
After installation, verify Node.js and NPM are installed by running the
following commands in your terminal:
node -v
npm -v
These commands will show the installed versions of Node.js and NPM.

NodeJS NPM Version

Step 3: Initialize a New Node.js Project


In the terminal, navigate to your project directory and run:
npm init -y
This will create a package.json file, which stores metadata about your
project, including dependencies and scripts.
Step 4: Install Packages with NPM
To install a package, use the following command
npm install <package-name>
For example, to install the Express.js framework
npm install express
This will add express to the node_modules folder and automatically
update the package.json file with the installed package information.
Step 5: Install Packages Globally
To install packages that you want to use across multiple projects, use the
-g flag:
npm install -g <package-name>
Step 6: Run Scripts
You can also define custom scripts in the package.json file under the
“scripts” section. For example:
{
"scripts": {
"start": "node app.js"
}
}
Then, run the script with
npm start

Node Callback Concept



A callback in Node is a non-blocking function that executes upon


task completion, enabling asynchronous processing. It facilitates
scalability by allowing Nodejs to handle multiple requests without
waiting for operations to conclude, as exemplified in file I/O
scenarios.
Explanation: The fs library is used for file-system operations.
The readFileSync() function is synchronous, halting program
execution until completion. This blocking behavior ensures that
the program reads the file before progressing further.
Example 1: Code for reading a file synchronously (blocking code)
in Nodejs. Create a text file inputfile1.txt with the following
content:
Hello Programmer!!!
Learn NodeJS with GeeksforGeeks
// Write JavaScript code

const fs = require("fs");
const filedata = fs.readFileSync('inputfile1.txt');

console.log(filedata.toString());

console.log("End of Program execution");

Events Module
Node.js has a built-in module, called "Events", where you can create-, fire-,
and listen for- your 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


You can assign event handlers to your own events with the EventEmitter
object.

In the example below we have created a function that will be executed when
a "scream" event is fired.

To fire an event, use the emit() method.

Example
var events = require('events');
var eventEmitter = new events.EventEmitter();

//Create an event handler:


var myEventHandler = function () {
console.log('I hear a scream!');
}

//Assign the event handler to an event:


eventEmitter.on('scream', myEventHandler);
//Fire the 'scream' event:
eventEmitter.emit('scream');

Express Framework

Express.js is a minimal and flexible web application framework that provides


a robust set of features to develop Node.js based web and mobile
applications. Express.js is one of the most popular web frameworks in the
Node.js ecosystem. Express.js provides all the features of a modern web
framework, such as templating, static file handling, connectivity with SQL and
NoSQL databases.

Node.js has a built-in web server. The createServer() method in its http
module launches an asynchronous http server. It is possible to develop a web
application with core Node.js features. However, all the low level
manipulations of HTTP request and responses have to be tediously handled.
The web application frameworks take care of these common tasks, allowing
the developer to concentrate on the business logic of the application. A web
framework such as Express.js is a set of utilities that facilitates rapid, robust
and scalable web applications.

Following are some of the core features of Express framework −

 Allows to set up middlewares to respond to HTTP Requests.


 Defines a routing table which is used to perform different actions based
on HTTP Method and URL.
 Allows to dynamically render HTML Pages based on passing arguments
to templates.

The Express.js is built on top of the connect middleware, which in turn is


based on http, one of the core modules of Node.js API.

Installing Express
The Express.js package is available on npm package repository. Let us install
express package locally in an application folder named ExpressApp.

D:\expressApp> npm init


D:\expressApp> npm install express --save

The above command saves the installation locally in the node_modules


directory and creates a directory express inside node_modules.

Hello world Example


Following is a very basic Express app which starts a server and listens on port
5000 for connection. This app responds with Hello World! for requests to the
homepage. For every other path, it will respond with a 404 Not Found.

var express = require('express');


var app = express();

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


res.send('Hello World');
})

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


console.log("Express App running at http://127.0.0.1:5000/");
})

Save the above code as index.js and run it from the command-line.

D:\expressApp> node index.js


Express App running at http://127.0.0.1:5000/

Visit http://localhost:5000/ in a browser window. It displays the Hello World


message.
REST API

REST stands for REpresentational State Transfer. REST is a well known


software architectural style. It defines how the architecture of a web
application should behave. It is a resource based architecture where
everything that the REST server hosts, (a file, an image, or a row in a table of
a database), is a resource, having many representations. REST was first
introduced by Roy Fielding in 2000.

REST recommends certain architectural constraints.

 Uniform interface
 Statelessness
 Client-server
 Cacheability
 Layered system
 Code on demand

These are the advantages of REST constraints −

 Scalability
 Simplicity
 Modifiability
 Reliability
 Portability
 Visibility

A REST Server provides access to resources and REST client accesses and
modifies the resources using HTTP protocol. Here each resource is identified
by URIs/ global IDs. REST uses various representation to represent a resource
like text, JSON, XML but JSON is the most popular one.
HTTP methods
Following four HTTP methods are commonly used in REST based architecture.

POST Method
The POST verb in the HTTP request indicates that a new resource is to be
created on the server. It corresponds to the CREATE operation in the CRUD
(CREATE, RETRIEVE, UPDATE and DELETE) term. To create a new resource,
you need certain data, it is included in the request as a data header.

Examples of POST request −

HTTP POST http://example.com/users


HTTP POST http://example.com/users/123

GET Method
The purpose of the GET operation is to retrieve an existing resource on the
server and return its XML/JSON representation as the response. It
corresponds to the READ part in the CRUD term.

Examples of a GET request −

HTTP GET http://example.com/users


HTTP GET http://example.com/users/123

PUT Method
The client uses HTTP PUT method to update an existing resource,
corresponding to the UPDATE part in CRUD). The data required for update is
included in the request body.

Examples of a PUT request −

HTTP PUT http://example.com/users/123


HTTP PUT http://example.com/users/123/name/Ravi

DELETE Method
The DELETE method (as the name suggest) is used to delete one or more
resources on the server. On successful execution, an HTTP response code
200 (OK) is sent.

Examples of a DELETE request −


HTTP DELETE http://example.com/users/123
HTTP DELETE http://example.com/users/123/name/Ravi

RESTful Web Services


Web services based on REST Architecture are known as RESTful web services.
These webservices uses HTTP methods to implement the concept of REST
architecture. A RESTful web service usually defines a URI, Uniform Resource
Identifier a service, which provides resource representation such as JSON and
set of HTTP Methods.

MONGODB with NODEJS


Async Await
Async Await are the modern tools in node for handling async operations
providing better redability to the code. This functions with async keyword
automatically returns a promise.
The functions need not to be chained one after another, simply await the
function that returns the Promise. But the function async needs to be
declared before awaiting a function returning a Promise.

MongoDB display data using nodejs

const{MongoClient}=require('mongodb');
const url = 'mongodb://0.0.0.0:27017';
const database = 'pj';
const Client = new MongoClient(url);

async function getData()


{
let result =await Client.connect();
let db = result.db(database);
let collection = db.collection('pj');
let response = await collection.find({}).toArray();
console.log(response);
}
getData();

Output

PS C:\Users\facul> node index.js

{ _id: new ObjectId('67567686e6ed140fdfea0524'), rollno: 16 },

{ _id: new ObjectId('6756949b440d2672fa2e04ed'), rollno: 14 }

MongoDB insert using Nodejs


const{MongoClient}=require('mongodb');
const url = 'mongodb://0.0.0.0:27017';
const database = 'pj';
const Client = new MongoClient(url);

async function getData()


{
let result =await Client.connect();
let db = result.db(database);
let collection = db.collection('pj');
let response = db.collection('pj').insertOne({rollno:14})
console.log(response);
}
getData();

MongoDB delete using Nodejs:

const{MongoClient}=require('mongodb');
const url = 'mongodb://0.0.0.0:27017';
const database = 'pj1';
const Client = new MongoClient(url);

async function getData()


{
let result =await Client.connect();
let db = result.db(database);
let collection = db.collection('pj1');
let response = db.collection('pj1').deleteOne({rollno:15})
console.log(response);
}
getData();

Mongodb-nodejs Join operations


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:

ordersGet your own Node.js Server


[
{ _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'
}
}
]).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

Which will give you this result:

[
{ "_id": 1, "product_id": 154, "status": 1, "orderdetails": [
{ "_id": 154, "name": "Chocolate Heaven" } ]
}
]

As you can see from the result above, the matching document from the
products collection is included in the orders collection as an array.

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.

ExampleGet your own Node.js Server


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();
});
});

Run example »

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

Which will give you this result:

[
{ _id: 58fdbf5c0ef8a50b4cdd9a86, name: 'Amy', address: 'Apple
st 652'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8e, name: 'Ben', address: 'Park
Lane 38'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8a, name: 'Betty', address: 'Green
Grass 1'},
{ _id: 58fdbf5c0ef8a50b4cdd9a90, name: 'Chuck', address: 'Main
Road 989'},
{ _id: 58fdbf5c0ef8a50b4cdd9a87, name: 'Hannah', address:
'Mountain 21'},
{ _id: 58fdbf5c0ef8a50b4cdd9a84, name: 'John', address:
'Highway 71'},
{ _id: 58fdbf5c0ef8a50b4cdd9a88, name: 'Michael', address:
'Valley 345'},
{ _id: 58fdbf5c0ef8a50b4cdd9a85, name: 'Peter', address:
'Lowstreet 4'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8b, name: 'Richard', address: 'Sky
st 331'},
{ _id: 58fdbf5c0ef8a50b4cdd9a89, name: 'Sandy', address: 'Ocean
blvd 2'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8c, name: 'Susan', address: 'One
way 98'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8d, name: 'Vicky', address:
'Yellow Garden 2'},
{ _id: 58fdbf5c0ef8a50b4cdd9a91, name: 'Viola', address:
'Sideway 1633'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8f, name: 'William', address:
'Central st 954'}
]

You might also like