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

node JS

Uploaded by

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

node JS

Uploaded by

shrikijaiswal
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 85

Node.

js
https://www.youtube.com/watch?v=nkB3_dIDC08
Java Script : Front end validation language
-Purpose: It was used for validating the
input data
-JS was running inside the browser
Browsers: were executing Javascript code
- Browsers were using JS V8 Engine to
convert JS to Machine Language for execution
Around 2009, they came up with this idea.
- Why can’t we use JS outside the browser,
run it like a server side script
- To run this like a server side script, need a
lot of libraries.
i) JS should be able to communicate with
the OS
ii) JS should be able to communicate with
the networks
iii) JS should be able to access the files
iv) should be able to communicate with the
NodeJS: JS + modules +
packages + JS V8 Engine : servers
enable JS to act like server v) Should also be working as a server
side script
We need a lot of libraries which are said to be
modules
NodeJS
• Its an open-source runtime
environment to run Javascript
code as a client-side script.
• To make JS run outside the
browser, we provide JS with V8
engine
• JS + modules + packages +
JS V8 Engine : enable us to
run JS outside the browser
• We call this environment as
NodeJS: JS + modules +
packages + JS V8 Engine : nodeJS
enable JS to act like server
side script
Why NodeJS?
• Although we have learned various server-side scripting
languages such as PHP, ASP, and JSP, what makes
Node.js a superior choice?
• nodeJS is more scalable and faster (not gonna
concentrate on why is scalable and faster)
• It is used by popular organizations across the globe

• Lets take a look at how to install nodeJS


Lets run the first javascript code
1. Create a folder named “nodejs” inside any of the drive “D:\VIT\23-
24\Winter\IP-Web Programming\KL ppts\Module 7\nodejs”
2. Open the command prompt and navigate into the created folder

3. Type code .
Vscode gets opened automatically

Create a “first.js” new file


first.js
console.log(“hope this works!!!..then life will
be great!!!");
How to run first.js ?
• Select Menu“Terminal” -> New Terminal
How to run first.js ?
• A new Terminal is opened below
How to run first.js ?
• On the Terminal, type node first.js
How to run first.js ?
• Installed nodeJS and run js file successfully.
Install Packages in nodeJS
• On terminal, type: npm install nodemon
• npm => node package manager : It manages a list of packages
that u can install for ur project
• Purpose of nodemon installation: is to automatically restart a
Node.js application and run source code whenever it detects
changes in the source code.
Install Packages in nodeJS
• On terminal, type: nodemon first.js
• Nodemon is gonna monitor this source code from now on for any
changes.
• If there is any changes in source code, its gonna to run the source code
automatically and output is obtained
Execute first.js

If u get Error like this?


Execute first.js

Check Installation: Ensure that nodemon was installed


globally or locally. You can check the installation by
running the following commands: npm list -g nodemon
npm list nodemon
Execute first.js
• Check Global Installation Path: If you have reinstalled
npm, verify that the global installation path is set up
correctly. To check the global installation path, you can run
the following command in PowerShell: npm config get
prefix

This will tell you the path where global packages are
installed. If it's not set to a path you expect, you can set it to
your desired path using: npm config set prefix "C:\Users\
svlek\AppData\Roaming\npm"
Execute first.js
Install nodemon: After ensuring the global path is set
correctly, try installing nodemon globally again: npm
install -g nodemon
Execute first.js
Run: nodemon first.js
Execute first.js
Temporarily Change Execution Policy:
1.Open a PowerShell window as an administrator.
2.Run the following command to temporarily change the execution
policy for the current session: Set-ExecutionPolicy -
ExecutionPolicy Bypass -Scope Process

3.This allows you to run scripts in the current PowerShell session. The
policy will revert back to its previous state when you close the
Execute first.js
Permanently Change Execution Policy:
1.Open a PowerShell window as an administrator.
2.Run the following command to permanently change the
execution policy:
Set-ExecutionPolicy RemoteSigned -Scope
CurrentUser
Execute first.js
Go back to nodeJS
Run: nodemon first.js
Execute first.js
In first.js, do some modification as :
console.log("hope this works!!!");

And save the file ctrl + s


After saving, Execution will start automatically in Terminal
Summary

• Learnt
• Why we need nodejs

• Installation of nodejs

• Installation of package called “nodemon” so that it picks up


the changes and runs the source code
Problem
Perform CRUD operations on MongoDB using node.js

• Open command prompt, type the following: code .

• VS code is opened now


Problem
Perform CRUD operations on MongoDB using node.js

• Check the version node : node -v


Install MongoDB
Install MongoDB
Install MongoDB
Install MongoDB
Install MongoDB
Install MongoDB
1. Go to C:/ Drive
2. Then C:\Program Files\MongoDB\Server\7.0\bin
3. Copy the path “C:\Program Files\MongoDB\Server\7.0\bin”
4. Search for “Environmental Variables” in windows Explore
5. Click “Environmental Variables” button
6. Under “System Variables” section, choose “Path”
7. New dialog box “Edit environment variable” is opened.
8. Click “New” button
9. Paste the copied path here “C:\Program Files\MongoDB\Server\7.0\
bin”
10. Give 3 OKs
Open MongoDB
1. Open command prompt in the following drive : type: mongod

2. U will get the information in next slide


Open MongoDB
1. Open command prompt in the following drive : type: mongod
Install MongoDB Shell
1. Change the package zip to msi and then give Download
Install MongoDB Shell
Install MongoDB Shell
1. Click Next and Finish
2. Open command Prompt and type mongod --version
Install MongoDB Shell
1. Click Next and Finish
2. Open command Prompt and type mongod –version
3. Type: mongosh
Install MongoDB Shell
1. Click Next and Finish
2. Open command Prompt and type mongod –version
3. Type: mongosh
4. In the test> show dbs
5. Type: use satishdb
Install MongoDB Shell
1. Click Next and Finish
2. Open command Prompt and type mongod –version
3. Type: mongosh
4. In the test> show dbs
5. Type: use satishdb
6. Type: db.createCollection("student")
7. Type: show collections;
Install MongoDB Shell
1. Click Next and Finish
2. Open command Prompt and type mongod –version
3. Type: mongosh
4. In the test> show dbs
5. Type: use satishdb
6. Type: db.createCollection("student")
7. Type: show collections;
8. Search(in windows explorer) for “Services” and ensure Mongodb
server is running
9. Ensure ur Mongodb server is running as a service on ur systems
10.While working with mongodb, this will prevent the “Connection Refusal
Open VSCODE & Install mongodb &
Check it
• npm install mongodb --save
• npm list mongodb
Exercise 1 Establishing connection with the database and
fetching all the databases

const {MongoClient} = require('mongodb');


Exercise 1 Establishing connection with the database and
fetching all the databases : first_dbconnection.js

const {MongoClient} = require('mongodb’);

async function main(){

const uri = "mongodb://127.0.0.1:27017/";


const client = new MongoClient(uri);
try {
// Connect to the MongoDB cluster
await client.connect();
// Make the appropriate DB calls
await listDatabases(client);
} catch (e) {
console.error(e);
}
finally { await client.close(); }
}
Exercise 1 Establishing connection with the database and
fetching all the databases : first_dbconnection.js(cont…)

main().catch(console.error);

async function listDatabases(client){


databasesList = await client.db().admin().listDatabases();

console.log("Databases:");
databasesList.databases.forEach(db => console.log(` - ${db.name}`));
};
Exercise 1 Establishing connection with the database and
fetching all the databases : first_dbconnection.js(cont…)

output
PS D:\VIT\23-24\Winter\IP-Web Programming\KL ppts\Module 7\nodejs>
nodemon first_dbconnection.js
[nodemon] 3.1.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node first_dbconnection.js`
Databases:
- admin
- config
- local
- satishdb
[nodemon] clean exit - waiting for changes before restart
Insert a record in the collection by named vscode in
database vitdb : first_ins.js
const {MongoClient} = require('mongodb’);

async function main(){

const uri = "mongodb://127.0.0.1:27017/";


const client = new MongoClient(uri);
try {
// Connect to the MongoDB cluster
await client.connect();

// Create a single new listing


await insertDocument(client,
{
name: "Satish",
summary: "Satish is teaching MongoDB"
}
);

}
Insert a record in the collection by named vscode in
database vitdb : first_ins.js (cont…)

catch (e) {
console.error(e);
} finally {
await client.close();
}
}

main().catch(console.error);

async function insertDocument(client, newListing){

const result = await client.db("vitdb").collection("vscode").insertOne(newListing);

console.log(`New listing created with the following id: ${result.insertedId}` );

}
Run it in Vscode First ….
Insert a record in the collection by named vscode in
database vitdb : first_ins.js (cont…)

output
PS F:\Winter Semester 2022-23\codedemo> node first.js
New listing created with the following id: 6432ba80e40381b7aa9547c9
PS F:\Winter Semester 2022-23\codedemo>

Record inserted on mongo database


> db.vscode.find();
{ "_id" : ObjectId("64327ce9bb103b2a3a353b7e"), "name" : "Mathew",
"course" : "testing db connection" }
{ "_id" : ObjectId("6432b9c59061f67fa5c2d6f5"), "name" : "Ram", "summary"
: "Testing Inserting a Record" }
{ "_id" : ObjectId("6432ba80e40381b7aa9547c9"), "name" : "Satish",
"summary" : "Satish is teaching MongoDB" }
Try on yourself
• Search for a document (search for document with the
name attribute as Satish)
• Reading Multiple Documents from Mongodb
• Reading all records from a collection in mongodb
• Updating a record using the username
• Deleting a document from the Collection
search for a document (search for document
with the name attribute as Satish)
search for a document (search for document with the name
attribute as Satish) : first_search.js

const {MongoClient} = require('mongodb’);

async function main(){

const uri = "mongodb://127.0.0.1:27017/";


const client = new MongoClient(uri);
try {
// Connect to the MongoDB cluster
await client.connect();

//search for one record


await findUser(client, "Satish");
}
catch (e) {
console.error(e);
}
search for a document (search for document with the name
attribute as Satish) : first_search.js (cont..)
finally {
await client.close();
}
}
main().catch(console.error);
async function findUser(client, username) {
const result = await
client.db("vitdb").collection("vscode").findOne({ name: username });

if (result) {
console.log(`Found a listing in the collection with the name '$
{username}':`);
console.log(result);
} else {
console.log(`No listings found with the name '${nameOfListing}'`);
}

}
search for a document (search for document with the name
attribute as Satish) : first_search.js (cont..)

output from terminal

PS F:\Winter Semester 2022-23\codedemo> node first.js


Found a listing in the collection with the name 'Satish':
{
_id: new ObjectId("6432ba80e40381b7aa9547c9"),
name: 'Satish',
summary: 'Satish is teaching MongoDB'
}
Reading Multiple Documents
from Mongodb
Reading Multiple Documents from Mongodb : first_ readmul.js

const {MongoClient} = require('mongodb’);

async function main(){

const uri = "mongodb://127.0.0.1:27017/";


const client = new MongoClient(uri);
try {
// Connect to the MongoDB cluster
await client.connect();

//search for one record


await findUsers(client, {name: 'Satish’});
}
catch (e) {
console.error(e);
}
Reading Multiple Documents from Mongodb : first_ readmul.js
(cont…)
finally {
await client.close();
}
}
main().catch(console.error);
async function findUsers(client, {username = 'Satish'} = {}) {
const cursor = await client.db("vitdb").collection("vscode"). .find({name:
'Satish' });

// Store the results in an array


const results = await cursor.toArray();

// Print the results


if (results.length > 0) {
results.forEach((result, i) => {
console.log();
console.log(`name: ${result.name}`);
console.log(` summary: ${result.summary}`);
});
}
Reading Multiple Documents from Mongodb : first_readmul.js
(cont…)

else {
console.log(`No listings found`);
}

output from terminal


PS F:\Winter Semester 2022-23\codedemo> node first.js

name: Satish
summary: Satish is teaching MongoDB

name: Satish
summary: another record
Reading all Records from a
collection in Mongodb
Reading all Records from a collection in Mongodb :
first_readall.js

const {MongoClient} = require(‘mongodb’);

async function main(){

const uri = "mongodb://127.0.0.1:27017/";


const client = new MongoClient(uri);
try {
// Connect to the MongoDB cluster
await client.connect();

//search for one record


await findUsers(client, {});
}
catch (e) {
console.error(e);
}
Reading all Records from a collection in Mongodb :
first_readall.js (cont..)
finally {
await client.close();
}
}
main().catch(console.error);
async function findUsers(client, {} = {}) {
const cursor = await client.db("vitdb").collection("vscode"). .find({});

// Store the results in an array


const results = await cursor.toArray();

// Print the results


if (results.length > 0) {
results.forEach((result, i) => {
console.log();
console.log(`name: ${result.name}`);
console.log(` summary: ${result.summary}`);
});
}
Reading Multiple Documents from Mongodb : first_readall.js (cont…)

else {
console.log(‘No listings found’);
}

output from terminal


PS F:\Winter Semester 2022-23\codedemo> node first.js
name: Mathew summary: undefined
name: Ram summary: Testing
Inserting a Record name: Satish
summary: Satish is teaching MongoDB
name: Satish summary: another record
Updating a record using the
username
Updating a record using the username : : first_search.js

const {MongoClient} = require('mongodb’);

async function main(){

const uri = "mongodb://127.0.0.1:27017/";


const client = new MongoClient(uri);
try {
// Connect to the MongoDB cluster
await client.connect();

await updateUserSummary(client, "Mathew", { summary:"Updated summary"});


}
catch (e) {
console.error(e);
}
Updating a record using the username : : first_search.js
(cont..)
finally {
await client.close();
}
}
main().catch(console.error);
async function updateUserSummary(client, username, updatedSummary)
{ const result = await
client.db("vitdb").collection("vscode").updateOne({ name: username },
{ $set: updatedSummary });

console.log(`${result.matchedCount} document(s) matched the query


criteria.`);
console.log(`${result.modifiedCount} document(s) was/were updated.`);
}
Updating a record using the username : : first_search.js
(cont..)

output from terminal


PS F:\Winter Semester 2022-23\codedemo> node first.js

1 document(s) matched the query criteria.


1 document(s) was/were updated.

Output in Database

> db.vscode.find();
{ "_id" : ObjectId("64327ce9bb103b2a3a353b7e"), "name" : "Mathew",
"course" : "testing db connection", "summary" : "Updated summary" }
{ "_id" : ObjectId("6432b9c59061f67fa5c2d6f5"), "name" : "Ram", "summary" :
"Testing Inserting a Record" }
{ "_id" : ObjectId("6432ba80e40381b7aa9547c9"), "name" : "Satish", "summary"
: "Satish is teaching MongoDB" }
{ "_id" : ObjectId("6432bf0a86b0db063f0ec8b3"), "name" : "Satish", "summary"
: "another record" }
Deleting a document from the
Collection
Deleting a document from the Collection: : first_del.js

const {MongoClient} = require('mongodb’);

async function main(){

const uri = "mongodb://127.0.0.1:27017/";


const client = new MongoClient(uri);
try {
// Connect to the MongoDB cluster
await client.connect();

await deleteByName(client, "Ram");

} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
Deleting a document from the Collection: : first_del.js (cont..)

main().catch(console.error);

async function deleteByName(client, nameOfUser) {


const result = await
client.db("vitdb").collection("vscode").deleteOne({ name: nameOfUser });
console.log(`${result.deletedCount} document(s) was/were deleted.`);
}
Deleting a document from the Collection: : first_del.js (cont..)

output from Terminal

PS F:\Winter Semester 2022-23\codedemo> node first.js


1 document(s) was/were deleted.

Database Output

> db.vscode.find();
{ "_id" : ObjectId("64327ce9bb103b2a3a353b7e"), "name" : "Mathew",
"course" : "testing db connection", "summary" : "Updated summary" }
{ "_id" : ObjectId("6432ba80e40381b7aa9547c9"), "name" : "Satish", "summary"
: "Satish is teaching MongoDB" }
{ "_id" : ObjectId("6432bf0a86b0db063f0ec8b3"), "name" : "Satish", "summary"
: "another record" }
>

You might also like