Unit 3 Nodejs
Unit 3 Nodejs
js
Node.js is an open-source and cross-platform JavaScript runtime
environment.
Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside
of the browser. This allows Node.js to be very performant.
A Node.js app runs in a single process, without creating a new thread for
every request. Node.js provides a set of asynchronous I/O primitives in its
standard library that prevent JavaScript code from blocking and generally,
libraries in Node.js are written using non-blocking paradigms.
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.
JavaScript Engine
JavaScript code we write cannot be understood by the computer
A JavaScript engine is a program that converts javascript code that
developers write into machine code that allows a computer to perform
specific tasks
JavaScript engines are typically developed by web browser vendors
V8 - Open-source JavaScript Engine developed by Google for Chrome
SpiderMonkey - The JavaScript Engine powering Mozilla Firefox
JavaScriptCore - Open-source JavaScript Engine developed by Apple for
Safari
Chakra - A JavaScript Engine for the original Microsoft Edge (The latest
version of edge uses V8
Features of Node.js
1. Extremely fast: Node.js is built on Google Chrome's V8 JavaScript Engine, so its
library is very fast in code execution.
2. I/O is Asynchronous and Event Driven: All APIs of Node.js library are
asynchronous i.e. non-blocking. So a Node.js based server never waits for an API
to return data. The server moves to the next API after calling it and a notification
mechanism of Events of Node.js helps the server to get a response from the
previous API call. It is also a reason that it is very fast.
3. Single threaded: Node.js follows a single threaded model with event looping.
4. Highly Scalable: Node.js is highly scalable because event mechanism helps the
server to respond in a non-blocking way.
5. No buffering: Node.js cuts down the overall processing time while uploading
audio and video files. Node.js applications never buffer any data. These
applications simply output the data in chunks.
6. Open source: Node.js has an open source community which has produced many
excellent modules to add additional capabilities to Node.js applications.
7. License: Node.js is released under the MIT license.
npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible
defaults.
package.json:
{
"name": "nodejstutorial",
"version": "1.0.0",
"description": "nodejs tutorial",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon index.js" /add “start” with nodemon utility
},
"author": "",
"license": "ISC",
"devDependencies": {
"i": "^0.3.7",
"nodemon": "^3.0.3"
}
}
Install nodemon:
npm install i --save-dev nodemon
nodemon is a tool that helps develop Node. js based applications by
automatically restarting the node application when file changes in the
directory are detected. nodemon does not require any additional
changes to your code or method of development.
process.argv.forEach((val, index)=>{
console.log(`${index}: ${val}`)
})
Placeholder Meaning
:bar The actual progress bar (like ######------)
:rate Speed (how many units/second)
:percent Percentage of completion
:etas Estimated time remaining (in seconds)
This tells the progress bar how many total ticks it will have.
total: 20 means it will complete after 20 .tick() calls.
const rl = require(‘node:readline’);
Once this code is invoked, the Node.js application will not terminate
until thereadline.Interface is closed because the interface waits for data
to be received on the input stream.
Example 2:
const readLine = require('readline')
const rl = readLine.createInterface({
input: process.stdin,
output:process.stdout,
})
rl.question(`What is your name?`, (name)=>{
console.log(`Hi, ${name}`);
rl.close();
})
Node.js Module
Module in Node.js is a simple or complex functionality organized in
single or multiple JavaScript files which can be reused throughout
the Node.js application.
Each module in Node.js has its own context, so it cannot interfere
with other modules or pollute global scope. Also, each module can
be placed in a separate .js file under a separate folder.
Local Modules
Local modules in Node.js are modules that you create within your own
project directory. They are typically files containing JavaScript code that
you create to encapsulate specific functionality or logic that you want
to reuse across different parts of your application.
Here's how you can create and use local modules in Node.js:
Create a JavaScript File: Create a new JavaScript file within your project
directory. This file will contain the code for your local module.
// myModule.js
function greet() {
console.log('Hello, world!');
}
Module Wrapper
In Node.js, every module is wrapped in a function by default, which
provides the module with certain variables as function parameters.
These parameters are:
exports: This is an object that is used to define what should be
exported from the module. When you assign properties or
methods to exports, they become accessible to other modules
that require the module.
require: This is a function that is used to import other modules or
files within the current module.
module: This is an object that represents the current module. It
provides information about the module, such as its filename,
exports, and whether it is the main module or a required module.
__filename: This is a string representing the filename of the
current module, including the full path to the file.
__dirname: This is a string representing the directory name of the
current module, including the full path to the directory.
Method Description
Example:
const path = require('path');
console.log(__filename)
console.log(__dirname)
console.log(path.basename(__filename))
console.log(path.basename(__dirname))
console.log(path.format(path.parse(__filename)))
console.log(path.isAbsolute(__filename))
Fs module: The File System module provides a way of working with the
computer's file system. Node.js includes fs module to access physical
file system. The fs module is responsible for all the asynchronous or
synchronous file I/O operations
Reading a File
Use the fs.readFile() method to read the physical file asynchronously.
fs.readFile(fileName [,options], callback_function(err, data))
filename: Full path and name of the file as a string.
options: The options parameter can be an object or string which can
include encoding and flag. The default encoding is utf8 and default flag
is "r".
callback: A function with two parameters err and data. This will get
called when readFile operation completes.
Writing a File
Use the fs.writeFile() method to write data to a file. If file already exists
then it overwrites the existing content otherwise it creates a new file
and writes data into it.
fs.writeFile(filename, data[, options], callback_function(err, data))
filename: Full path and name of the file as a string.
Data: The content to be written in a file.
options: The options parameter can be an object or string which can
include encoding, mode and flag. The default encoding is utf8 and
default flag is "r".
callback: A function with two parameters err and data. This will get
called when write operation completes.
Open File
Alternatively, you can open a file for reading or writing using the
fs.open() method.
fs.open(path, flags[, mode], callback_function())
path: Full path with name of the file as a string.
flags: A string specifying the file access mode, e.g., 'r', 'w', 'a'.
'r': Open for reading.
'w': Open for writing (creates the file if it does not exist, or
truncates if it does).
'a': Open for appending (creates the file if it does not exist).
Mode: The mode for read, write or readwrite. Defaults to 0666
readwrite.
callback: A function with two parameters err and data. This will get
called when file open operation completes.
Delete File
Use the fs.unlink() method to delete an existing file.
fs.unlink(path, callback_function());
Flags
The following table lists all the flags which can be used in read/write
operation.
Flag Description
R Open file for reading. An exception occurs if the file does not
exist.
r+ Open file for reading and writing. An exception occurs if the
file does not exist.
Rs Open file for reading in synchronous mode.
rs+ Open file for reading and writing, telling the OS to open it
synchronously. See notes for 'rs' about using this with caution.
W Open file for writing. The file is created (if it does not exist) or
truncated (if it exists).
Wx Like 'w' but fails if path exists.
w+ Open file for reading and writing. The file is created (if it does
not exist) or truncated (if it exists).
wx+ Like 'w+' but fails if path exists.
A Open file for appending. The file is created if it does not exist.
Ax Like 'a' but fails if path exists.
a+ Open file for reading and appending. The file is created if it
does not exist.
ax+ Like 'a+' but fails if path exists.
Example:
var fs = require('fs');
const fs = require('fs')
const a = fs.readFileSync('./file.txt', "utf-8")
console.log(a)
fs.readFile("./file.txt", "utf-8",
(error, data)=>{
if(error){
throw error
}
console.log(data)
}
)
Node.js Timer
Node.js Timer functions are global functions. You don't need to use
require() function in order to use timer functions. Let's see the list of
timer functions.
The timers module contains functions that can execute code after a
certain period of time. You do not need to import the timer module
explicitly, as it is already globally available across the emulated
browser JavaScript API.
Timers module is mainly categorised into two categories
Scheduling Timers − This timer schedules the task to take place after a
certain instant of time.
o setImmediate()
o setInterval()
o setTimeout()
Cancelling Timers − This type of timers cancels the scheduled tasks
which is set to take place.
o ClearImmediate()
o clearInterval()
o clearTimeout()
Scheduling Timers
1. setTimeout() Method
The setTimeout() method schedules the code execution after a
designated number of milliseconds. Only after the timeout has
occurred, the code will be executed. The specified function will be
executed only once. This method returns an ID that can be used in
clearTimeout() method.
Syntax
setTimeout(function, delay, [args])
setTimeout(function () {
// Will be printed after 2 seconds
return console.log(str);
}, 2000);
2. setImmediate() Method
setImmediate(): setImmediate prioritizes a callback to run immediately
after the current phase of the event loop
Syntax
setImmediate(function, [args])
// Setting timeout for the function
setTimeout(function () {
}, 5000);
setImmediate(function () {
});
Output
3. setInterval() Method
setInterval() executes the code after the specified interval. The
function is executed multiple times after the interval has passed. The
function will keep on calling until the process is stopped externally or
using code after specified time period.
Syntax
setInterval(function, delay, [args])
setInterval(function() {
console.log('Good Morning !');
}, 1000)
Output
Good Morning !
Good Morning !
Good Morning !
Good Morning !
Good Morning !
4.clearImmediate() Method
This method clears the Immediate timer object that is created by the
setImmediate() method.
Syntax
clearImmediate(timer)
Example:
var timer = setImmediate(function A() {
console.log("Timer set");
} );
clearImmediate(timer);
console.log("Timer cancelled");
5.clearInterval() Method
This method clears the Immediate timer object that is created by the
setInterval() method.
Syntax
clearInterval(timer)
Example
var si = setInterval(function A() {
return console.log("Setting Intevals for 500 ms !");
}, 500);
6.clearTimeout() Method
This method clears the Immediate timer object that is created by the
setTimeout() method.
Syntax
clearTimeout(timerObject)
var timer = setTimeout(function A() {
return console.log("Good Morning!");
}, 500);
// timer2 will be executed
var timer2 = setTimeout(function B() {
return console.log("Good Evening!");
}, 500);
clearTimeout(timer);
Node.js Events
Custom Event using EventEmitter class
Much of the Node.js core API is built around an idiomatic
asynchronous event-driven architecture in which certain kinds of
objects (called "emitters") emit named events that cause Function
objects ("listeners") to be called.
Custom events are often used in scenarios where different parts of
your application need to communicate or respond to specific actions,
providing a flexible and intentional event-driven architecture.
Custom events are triggered in Node.js when you explicitly call the
emit() method on an instance of the EventEmitter class. Unlike
browser-based events like the click event, which are automatically
triggered by user actions (e.g., clicking a button), custom events in
Node.js are manual and intentional.
User-Initiated Action (Browser Click Event):
o Action: User clicks a button.
o Trigger: The browser automatically triggers the associated click event
for that button.
Custom Event (Node.js EventEmitter):
o Action: You explicitly call emit() to trigger a custom event.
o Trigger: You manually trigger the custom event by calling emit() on an
instance of EventEmitter
Step 1: Import event module
Step 2: Create an instance of the EventEmitter() class
Step3: Define the event (Event handler) using on()
Step4: Trigger the event using emit()
Syntax:
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
// Custom event handler
myEmitter.on('customEvent', () => {
console.log('Custom event triggered!');
});
// Triggering the custom event
myEmitter.emit('customEvent');
Extending EventEmitter
You can extend the EventEmitter class to create more structured event-
based systems.
Example:
const EventEmitter = require('events')
var eventEmitter = new EventEmitter();
eventEmitter.on('order', (price, quantity) => {
console.log(`Order received: ${price} & ${quantity}`);
});
eventEmitter.on('order', (price)=>{
if(price>500){
console.log(`Serving complimentary drink `)
}
})
eventEmitter.emit('order', '500', '2');
Handling Events Only Once:
In order to handle events just one time, we can use the `once` method.
It has a signature that is similar to the `on` method:
emitter.once(eventName, listener)
Example:
const EventEmitter = require('events');
const customEmitter = new EventEmitter();
customEmitter.once('event1', (data) => console.log(data));
customEmitter.emit('event1', 'event 1 emitted');
customEmitter.emit('event1', 'event 1 emitted');
Error Handling:
try {
sporadicError();
customEmitter.emit('data', 'That was successful');
} catch (err) {
customEmitter.emit('error', err.message);
}
Usecases:
1. Chat Application (Message Events): use custom events to handle
new messages.
2. File Processing System: Emit events during different stages of file
processing (e.g., uploaded, processed, completed).
const EventEmitter = require('events');
requestHandler.on('data', () => {
console.log('Processing request data...');
});
requestHandler.on('end', () => {
console.log('Request handling completed.');
});
Node.js Process
The process object in Node.js is a global object that can be accessed
inside any module without requiring it. There are very few global
objects or properties provided in Node.js and process is one of them.
It is an essential component in the Node.js ecosystem as it provides
various information sets about the runtime of a program.
The process object in Node.js is a global object, although it is defined
in process module. It is an instance of EventEmitter class.
The process object provides information on current Node.js process.
With the help of a number of methods and properties associated
with this object, it is possible to control the current Node.js process.
Process Events
The process object is an instance of EventEmitter and emits the
following events −
Sr.No. Event & Description
Exit
Emitted when the process is about to exit. There is no way
1 to prevent the exiting of the event loop at this point, and
once all exit listeners have finished running, the process
will exit.
BeforeExit
This event is emitted when node empties its event loop
and has nothing else to schedule. Normally, the node exits
2
when there is no work scheduled, but a listener for
'beforeExit' can make asynchronous calls, and cause the
node to continue.
UncaughtException
Emitted when an exception bubbles all the way back to the
3 event loop. If a listener is added for this exception, the
default action (which is to print a stack trace and exit) will
not occur.
Warning
The 'warning' event is emitted whenever Node.js emits a
4 process warning. A process warning is similar to an error in
that it describes exceptional conditions that are being
brought to the user's attention.
Example
In the following code, the beforeExit event of the process object is
associated with a callback arrow function. Similarly the exit event calls
another callback function. The function on beforeExit runs first,
followed by the one on exit event.
process.on('beforeExit', (code) => {
console.log('A beforeExit event occured with code: ', code);
});
process.on('exit', (code) => {
console.log('Process exit event with code: ', code);
});
OUTPUT:
This message is displayed first.
Execution Completed
A beforeExit event occured with code: 0
Process exit event with code: 0
Exited with status code: 0
Process Methods
abort()
The abort() method immediately terminates the current process and
then creates a core file.
Example
The following program prints a message to the console after every one
second, and terminates the loop after 5 seconds as the abort() function
is called.
Example:
const abortfunction = () => {
console.log('Start...');
setInterval((function() {
return console.log('Hello World');
}), 1000);
setTimeout((function() {
return process.abort();
}), 5000);
};
abortfunction();
Output
Start...
Hello World
Hello World
Hello World
Hello World
The termination is followed by a long core file output.
chdir()
This method changes the current working directory of the Node.js
process or throws an exception if doing so fails (for instance, if the
specified directory does not exist).
cwd()
The process.cwd() method returns the current working directory of the
Node.js process.
Example:
console.log(`Starting directory: ${process.cwd()}`);
try {
process.chdir('../timers');
console.log(`New directory: ${process.cwd()}`);
} catch (err) {
console.error(`chdir: ${err}`);
}
exit()
This method terminates the current process synchronously with an exit
status of code (default is 'success' code 0). Node.js will not terminate
until all the 'exit' event listeners are called.
console.log('Code running');
process.on('exit', function(code) {
return console.log(`exiting with the error code : ${code}`);
});
setTimeout((function() {
return process.exit(0); //after 5 sec
}), 5000);
memoryUsage()
This function returns an object describing the memory usage of the
Node.js process measured in bytes.
console.log(process.memoryUsage());
process.versions
To explore we will use one of its properties which is called
process.versions. This property tells us the information about Node.js
version we have installed. It has to be used with -p flag.
> node -p "process.versions"
argv
Using argv you can always access arguments that are passed in a
command line. argv is an array which has Node itself as the first
element and the absolute path of the file as the second element.
From the third element onwards it can have as many arguments as
you want.
This property returns an array containing the command-line
arguments passed when the Node.js process was launched. You can
pass arguments to the script to be executed from the command line.
The arguments are stored in an array process.argv.
The 0th element in the array is the node executable,
first element is the JavaScript file, followed by the arguments
passed.
Example:
const args = process.argv;
args.forEach(function(val, index, array) {
console.log(index + ': ' + val);
});
const n1 = args[2];
console.log("Hello,", n1);
process.pid
property returns the PID of the process.
console.log(process.pid)
HTTP module
The HTTP module provides a way of making Node.js transfer data over
HTTP (Hyper Text Transfer Protocol).
var http = require('http');
HTTP Properties and Methods
Method Description
server.listen(4000, ()=>{
console.log("Server running")
})
Http request
Example1:
const http = require('http');
// Define the host and port
const hostname = '127.0.0.1';
const port = 4000;
Example2:
const http = require('http');
const options = {
hostname: 'www.example.com',
port: 80,
path: '/',
method: 'GET'
};
req.end();
if (req.url == '/data') {
res.writeHead(200, { 'Content-Type':
'application/json' });
res.write(JSON.stringify({ message: "Hello
World"}));
res.end();
}
});
server.listen(5000);
/* const obj = {
"name": "ABC",
"Age": 25
}; */
const server = htt.createServer((req, res)=>{
res.writeHead(200)
//reading json response
/* res.end(JSON.stringify(obj)) */
const fs = require('fs')
//JSON.parse() will convert the json file into java script obj
res.status(200).json(/* {
status: "sucess",
data: {
movies: movie
} */
movie
} )
app.listen(port, ()=>{
console.log('Server running')
})
HTTP methods
Following four HTTP methods are commonly used in REST based
architecture.
GET Method
The get method is a kind of HTTP request that a client makes to request
some data from the server
The get method comes with two parameters: the first is the URL, which
means the URL for which the method is listening, and the second is the
callback function, where that particular callback function takes two
default arguments: one is a request made by the client, and the other is
a response that will be sent to the client.
Syntax:
app.get("URL", (req,res)=> { }
)
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 term. To create a new resource, you need certain data,
it is included in the request as a data header.
The post method is used to send data from the client side to the
server side that will be further stored in the database. Suppose in an
application, the user registers with their credentials and details to
receive those details in the backend through the request body, and
storing that data in the database will be achieved under the post
method.
Similarly, the post method contains two parameters:the first is the
URL, which means the URL for which the method is listening, and the
second is the callback function, where that particular callback
function takes two default arguments: one is a request made by the
client, and the other is a response that will be sent to the client.
The post-request body contains the data sent by the client, and this
data can only be accessed after parsing it into JSON.
Syntax:
app.post("URL", (req,res)=>{} )
PUT Method
The put method is used to update the data that is already present in
the database. Suppose in an application you are updating your
name, so to update that name, you need to call a PUT method
request from the client side to the server side, and that data will
again be sent in the body of the request, and once the data is
received on the server, the data will be updated in the database.
Similarly, the put method contains two parameters:the first is the
URL, which means the URL for which the method is listening, and the
second is the callback function, where that particular callback
function takes two default arguments: one is a request made by the
client, and the other is a response that will be sent to the client.
Again the data wants to client update will comes under body section
of request.
Syntax:
app.put("URL",(req,res)=>{})
DELETE Method
Delete is one of the most commonly used HTTP methods; it is used to
delete particular data from a database. Suppose you are using an
application consisting of notes. When you click on delete any note, it
will make an HTTP delete request to the server and pass the ID of that
particular note in the body of the request. Once that ID is received by
the server, it will delete that particular note from Database.
Similarly, the delete method contains two parameters:the first is the
URL, which means the URL for which the method is listening, and the
second is the callback function, where that particular callback function
takes two default arguments: one is a request made by the client, and
the other is a response that will be sent to the client.
Again the ID will be comes under body section of request.
Syntax:
app.delete("URL",(req,res)=>{})
HTTP POST
Sr.No. URI Result
Method body
Show details of a
4 /:id GET empty
movie.
List Movies
Let's implement the first route in our RESTful API to list movies using
the following code in a index.js file
const http = require('http')
const fs = require('fs')
//JSON.parse() will convert the json file into java script obj
res.status(200).json(movie)
} )
app.listen(port, ()=>{
console.log('Server running')
})
app.get('/api/v1/movies/:id', (req,res)=>{
let id = req.params.id * 1;
res.status(200).json(find_movie)
if(!find_movie){
return res.status(404).json({
"status": "Failed",
})
})
app.listen(port, ()=>{
console.log('Server running')
})
const fs = require('fs')
app.use(express.json())
//JSON.parse() will convert the json file into java script obj
movie.push(newMovie)
//res.status(201).json(movie)
res.status(201).json(movie)
})
//console.log(req.body)
//res.send('created')
})
app.listen(port, ()=>{
console.log('Server running')
})
const fs = require('fs')
app.use(express.json())
app.put('/api/v1/movies/:id', (req,res)=>{
let id = req.params.id * 1;
let m_update= movie.find(el => el.id===id)
movie[index] = updated_movie
res.status(201).json(updated_movie)
})
})
app.listen(port, ()=>{
console.log('Server running')
})
const fs = require('fs')
app.use(express.json())
app.delete('/api/v1/movies/:id', (req,res)=>{
const id = parseInt(req.params.id)
movie.splice(index,1)
res.status(201).json(movie)
})
if(!del_movie){
return res.status(404).json({
status: "fail",
})
})
app.listen(port, ()=>{
console.log('Server running')
})
Express.js
Node JS is a fast JavaScript runtime environment that we use to build
server-side applications, but it does not know how to perform
serving files, handling requests, and handling HTTP methods, so this
is where express js comes in.
Express is a popular unopinionated web framework, written in
JavaScript and hosted within the Node.js runtime environment. This
module explains some of the key benefits of the framework, how to
set up your development environment and how to perform common
web development and deployment tasks.
Express JS is a Node.js framework designed to build API's web
applications cross-platform mobile apps quickly and make node is
easy.
Install Express.js
Firstly, you have to install the express framework globally to create web
application using Node terminal. Use the following command to install
express framework globally.
npm install -g express
The first argument is the singular name of the collection that will be
created for your model (Mongoose will create the database collection
for the above model SomeModel above), and the second argument is
the schema you want to use in creating the model.
Schema types (fields)
A schema can have an arbitrary number of fields — each one
represents a field in the documents stored in MongoDB. An example
schema showing many of the common field types and how they are
declared is shown below.
const schema = new Schema({
name: String,
living: Boolean,
updated: { type: Date, default: Date.now() },
age: { type: Number, min: 18, max: 65, required: true },
array: [],
});
Example:
const breakfastSchema = new Schema({
eggs: {
type: Number,
min: [6, "few breads"],
max: 12,
required: [true, "Why no breads?"],
},
drink: {
type: String,
enum: ["Coffee", "Tea", "Water"],
},
});
The built-in validators include:
All SchemaTypes have the built-in required validator. This is used to
specify whether the field must be supplied in order to save a document.
Numbers have min and max validators.
Strings have:
o enum: specifies the set of allowed values for the field.
o match: specifies a regular expression that the string must match.
o maxLength and minLength for the string
Using models
Once you've created a schema you can use it to create models. The
model represents a collection of documents in the database that you
can search, while the model's instances represent individual documents
that you can save and retrieve.
Creating and modifying documents
To create a record you can define an instance of the model and then call
save() on it. The examples below assume SomeModel is a model (with a
single field name) that we have created from our schema.
// Create an instance of model SomeModel
const awesome_instance = new SomeModel({ name: "awesome" });
// Save the new model instance asynchronously
awesome_instance.save();
You can also use create() to define the model instance at the same
time as you save it. Below we create just one, but you can create
multiple instances by passing in an array of objects.
SomeModel.create({ name: "also_awesome" });
Insert Documents
const { MongoClient } = require('mongodb')
// Insert to database
client.db('students').collection('students').insertOne({
name: 'Alice',
email: 'alice@example.com'
}).then((res) => {
console.log(res)
client.close()
}).catch((err) => console.log(err))
Update/Delete Documents
const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')
// Update to database
client.db('students').collection('students')
.updateOne({ name: 'Alice' },
{
$set:
{ email: 'Alice12@example.com' }
})
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => console.log(err))
const { MongoClient } = require('mongodb')
// Delete to database
client.db('students').collection('students')
.deleteOne({ name: 'Amyporter' })
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => console.log(err))