0% found this document useful (0 votes)
12 views66 pages

Unit 3 Nodejs

Node.js is an open-source, cross-platform JavaScript runtime environment built on Google's V8 engine, allowing for efficient and non-blocking I/O operations. It is primarily used for building network applications like web servers and supports various types of applications through its asynchronous and event-driven architecture. The document also covers features, module types, core modules, and practical examples of using Node.js, including package management with npm and handling environment variables.

Uploaded by

shuklasunny1324
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views66 pages

Unit 3 Nodejs

Node.js is an open-source, cross-platform JavaScript runtime environment built on Google's V8 engine, allowing for efficient and non-blocking I/O operations. It is primarily used for building network applications like web servers and supports various types of applications through its asynchronous and event-driven architecture. The document also covers features, module types, core modules, and practical examples of using Node.js, including package management with npm and handling environment variables.

Uploaded by

shuklasunny1324
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 66

Introduction to Node.

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 name: (nodejstutorial)


version: (1.0.0)
description: nodejs tutorial
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)

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.

npm: Node Package Manager, used to install Node.js packages.


install: Command to install a package.
--save-dev: Adds the package as a development dependency in your
package.json.

To exit from the nodejs execution use ctrl+c OR


Exit programmatically in index.json file
process.exitCode = 1;
Create .env file to add environment variables.
Environment variables offer information on the process's operating
environment (producton, development, build pipeline, and so on).
Environment variables in Node are used to store sensitive data such as
passwords, API credentials, and other information that should not be
written directly in code. Environment variables must be used to
configure any variables or configuration details that may differ between
environments.

Environment variables are already included in the Node.js ecosystem,


which gives them a significant benefit over alternative configuration
choices such as a config.js or config.json file.

How to Set up and read a .env file ?

The dotenv package for handling environment variables is the most


popular option in the Node.js community. You can create an.env file in
the application's root directory that contains key/value pairs defining
the project's required environment variables. The dotenv library reads
this.env file and appends it to process.env.

Install npm package dotenv


npm i dotenv
npm i nodemon

Start a node repl console


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.
The node:repl module provides a Read-Eval-Print-Loop (REPL)
implementation that is available both as a standalone program or
includible in other applications. It can be accessed using:
const repl = require('node:repl');

Creating an argument and access it in .js file


On terminal
Process is a global module and argv is a property of process.
node argument.js name=pratiksha
Argument.js
//reading arg i js file
//console.log(process.argv.slice(2)[0]);

process.argv.forEach((val, index)=>{
console.log(`${index}: ${val}`)
})

To read the argument values, use minimist package


Install
Npm i minimist
Add the argument
node argument.js --name=pratiksha
In argument.js file
const minimist = require("minimist");
const arg = minimist(process.argv.slice(2));
console.log(arg.name)
Adding ProcessBar on consolg
Output.js
const ProgressBar = require('progress');
const bar = new ProgressBar("downloading [:bar]
:rate/bps :percent :etas", {
total: 20,
})

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.

 Each tick moves the progress bar forward.

Adding color using chalk package


npm i chalk

const time = setInterval(()=>{


bar.tick();
if(bar.complete){
clearInterval(time)
}
}, 1000)
module "readline"
The node:readline module provides an interface for reading data from a
Readable stream (such as process.stdin) one line at a time.
To use the promise-based APIs:
import * as readline from 'node:readline/promises';
To use the callback and sync APIs:
import * as readline from 'node:readline';

const rl = require(‘node:readline’);

The following simple example illustrates the basic use of the


node:readlinemodule.

import * as readline from 'node:readline/promises';


import { stdin as input, stdout as output } from 'node:process';
const rl = readline.createInterface({ input, output });
const answer = await rl.question('What do you think of Node.js? ');
console.log(`Thank you for your valuable feedback: ${answer}`);
rl.close();

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

The prompt-sync module is a function that creates prompting


functions, so you need to call prompt-sync in order to get your actual
prompting function.

const pr= require('prompt-sync')();


const name = pr("What is your name? ");
console.log(`Hi, ${name}`)

NPM - Node Package Manager


 Node Package Manager (NPM) is a command line tool that installs,
updates or uninstalls Node.js packages in your application. It is also
an online repository for open-source Node.js packages.
 NPM is included with Node.js installation. After you install Node.js,
verify NPM installation using npm -v
NPM commands
1) Create package.json filr
Npm init
2) Npm uninstall: command will uninstall ExpressJS
npm uninstall express
3) Npm update: command will update the existing ExpressJS module
to the latest version.
npm update express
4) Npm -g: If you have an older version of NPM then you can update
it to the latest version using the following command.
npm install npm –g
5) To access NPM help, write npm help in the command prompt or
terminal window.
Npm help

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.

Node.js Module Types


Node.js includes three types of modules:
I. Core Modules (Built-in modules)
II. Local Modules
III. Third Party Modules

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!');
}

// Export the greet function


module.exports = greet;
Using the Local Module:
 Require the Module: In another JavaScript file within your project
directory, you can require the local module using require().
// app.js
const myModule = require('./myModule');
// Use the functionality from the local module
myModule();

An Immediately Invoked Function Expression (IIFE)


 An Immediately Invoked Function Expression (IIFE) is a common
JavaScript pattern used to execute a function immediately after it's
defined.
 This pattern is often employed to create a new scope for variables
and to prevent polluting the global namespace. In Node.js, you can
use IIFEs in the same way you would in browser-based JavaScript.
// Define and execute an IIFE
(function () {
console.log('This is an IIFE running in Node.js');
})();
 (function () { ... }): This is the syntax for defining an anonymous
function expression in JavaScript. The function is wrapped in
parentheses to denote that it's an expression.
 (): Immediately after the function definition, you see another set
of parentheses. This set of parentheses is what actually invokes
the function immediately after its definition.

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.

(function(exports, require, module, __filename, __dirname){


const res = 'Morning';
console.log(res);
}
) ();

Export pattern in node.js


1. Default Exports:
You can export a default value using module.exports.
2. Exporting with Named Exports:
You can use exports as a shorthand for module.exports to export
multiple items from a module.
// user.js
exports.getUserById = function(id) {
// Logic to get user by ID
};
3. Exporting Multiple Functions or Objects:
// math.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = {
add: add,
subtract: subtract
};

Importing JSON file


// data.json
{
"name": "Bright",
"age": 30,
}
// index.js
const data = require('./data.json');
console.log(data.name); // Output: Brigh
console.log(data.age); // Output: 30

Node.js Core Modules


Node.js is a light weight framework. The core modules include bare
minimum functionalities of Node.js. These core modules are compiled
into its binary distribution and load automatically when Node.js process
starts. However, you need to import the core module first in order to
use it in your application.
The following table lists some of the important core modules in
Node.js.
Core Module Description
http http module includes classes, methods and events to
create Node.js http server.
url url module includes methods for URL resolution and
parsing.
querystring querystring module includes methods to deal with
abc….?attribute=value query string.
path path module includes methods to deal with file
paths.
fs fs module includes classes, methods, and events to
work with file I/O.
util util module includes utility functions useful for
programmers.

Path module: The Path module provides a way of working with


directories and file paths.
var path = require('path');
Path Properties and Methods

Method Description

basename() Returns the last part of a path

delimiter Returns the delimiter specified for the platform


dirname() Returns the directories of a path

extname() Returns the file extension of a path

format() Formats a path object into a path string

isAbsolute() Returns true if a path is an absolute path, otherwise


false

join() Joins the specified paths into one

normalize() Normalizes the specified path

parse() Formats a path string into a path object

Posix Returns an object containing POSIX specific


properties and methods

relative() Returns the relative path from one specified path to


another specified path

resolve() Resolves the specified paths into an absolute path

Sep Returns the segment separator specified for the


platform

win32 Returns an object containing Windows specific


properties and methods

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

fs.writeFileSync('./file.txt', 'file written')


fs.writeFile('./file.txt', ' Write async', {flag:"a"},
(err)=>{
if(err){
throw err
}
console.log('msg updated')
})

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])

let str = 'Scheduling timer!';

setTimeout(function () {
// Will be printed after 2 seconds
return console.log(str);
}, 2000);

// This will be printed immediately


console.log('Executing setTimeout() method');
Output
Executing setTimeout() method
Scheduling timer!

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 () {

console.log('setTimeout() function running');

}, 5000);

// Running this function immediately before any other

setImmediate(function () {

console.log('setImmediate() function running');

});

Output

setImmediate() function running

setTimeout() function running

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

// Cleared the interval from 1000 ms


setTimeout(function() {
clearInterval(si);
}, 1000);

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');

 emit is used to trigger an event


 on is used to add a callback function that's going to be executed when
the event is triggered

Extending EventEmitter
You can extend the EventEmitter class to create more structured event-
based systems.

const EventEmitter = require('events');


class MyEmitter extends EventEmitter {}

// Create an instance of the custom emitter


const myEmitter = new MyEmitter();

// Add an event listener


myEmitter.on('sayHi', (name) => {
console.log(`Hi, ${name}!`);
});

// Emit the event


myEmitter.emit('sayHi', 'Bob');

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:

In Node.js, most of the core API follow a pattern called “Error-first


callbacks”, which means that if there were any errors, those should be
the first argument for the callback function.

A generic snippet to represent the idea could be as follows:

fs.readFile('data.csv', function(err, data) {


if (err) {
console.log('Error Found:' + err);
throw err;
}
console.log(data);
});

But with event emitters, we follow a slightly different approach to


handling errors. Since the emitters can emit custom events, an error
event could be emitted when we encounter one and we could attach a
listener with a callback that will act as the error handler.
const EventEmitter = require('events');
const customEmitter = new EventEmitter();

const sporadicError = () => {


const diceRoll = Math.random();
if (diceRoll >= 0.6) {
throw new Error('An error occurred in the application');
}
};

customEmitter.on('data', (data) => console.log(data));


customEmitter.on('error', (error) => console.log(error));

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');

class FileProcessor extends EventEmitter {}

const fileProcessor = new FileProcessor();

// Listener for file upload


fileProcessor.on('upload', (fileName) => {
console.log(`File "${fileName}" uploaded successfully.`);
// Trigger the processing event
fileProcessor.emit('process', fileName);
});

// Listener for file processing


fileProcessor.on('process', (fileName) => {
console.log(`Processing file: "${fileName}"...`);
setTimeout(() => {
fileProcessor.emit('complete', fileName);
}, 2000);
});

// Listener for processing complete


fileProcessor.on('complete', (fileName) => {
console.log(`File "${fileName}" processed successfully.`);
});

// Emit the upload event


fileProcessor.emit('upload', 'document.pdf');

3. HTTP Server Event Handling: Manage HTTP request lifecycle


using custom events.
const http = require('http');
const EventEmitter = require('events');

class RequestHandler extends EventEmitter {}

const requestHandler = new RequestHandler();

requestHandler.on('start', (req) => {


console.log(`Received request for: ${req.url}`);
});

requestHandler.on('data', () => {
console.log('Processing request data...');
});

requestHandler.on('end', () => {
console.log('Request handling completed.');
});

// Create an HTTP server


const server = http.createServer((req, res) => {
requestHandler.emit('start', req);
requestHandler.emit('data');
setTimeout(() => {
requestHandler.emit('end');
res.end('Response sent!');
}, 1000);
});

// Start the server


server.listen(3000, () => console.log('Server running on
http://localhost:3000'));
4. Real-Time Stock Price Updates: Notify users of stock price
changes.
const EventEmitter = require('events');

class StockMarket extends EventEmitter {}

const stockMarket = new StockMarket();

// Listener for stock price updates


stockMarket.on('priceUpdate', (stock, price) => {
console.log(`Stock: ${stock}, New Price: $${price}`);
});

// Emit price updates


stockMarket.emit('priceUpdate', 'AAPL', 145.32);
stockMarket.emit('priceUpdate', 'GOOG', 2789.50);

5. Authentication System: Emit events for login, logout, and account


lockout.
Example:
User Registration Interface that uses custom events to process user
registration.
const EventEmitter = require('events');
const readline = require('readline');

// Custom EventEmitter class for user registration


class UserRegistration extends EventEmitter {}

const userRegistration = new UserRegistration();

// Define custom events


userRegistration.on('register', (user) => {
console.log(`\nProcessing registration for ${user.username}...`);

// Step 1: Send welcome email


console.log(`Sending welcome email to ${user.email}...`);
setTimeout(() => {
console.log(`Welcome email sent to ${user.email}`);

// Trigger next event: log user details


userRegistration.emit('log', user);
}, 1000);
});

userRegistration.on('log', (user) => {


console.log(`Logging user details for ${user.username}...`);
setTimeout(() => {
console.log(`User details logged for ${user.username}`);

// Trigger next event: notify admin


userRegistration.emit('notifyAdmin', user);
}, 500);
});

userRegistration.on('notifyAdmin', (user) => {


console.log(`Notifying admin about the new user: $
{user.username}...`);
setTimeout(() => {
console.log(`Admin notified about user: ${user.username}`);
console.log('\nUser registration process completed successfully!\n');
}, 500);
});

// Create a user registration interface


const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});

// Prompt user for input


rl.question('Enter your username: ', (username) => {
rl.question('Enter your email: ', (email) => {
const newUser = { username, email };
console.log(`\nWelcome, ${username}! Starting the registration
process.`);

// Trigger the 'register' event


userRegistration.emit('register', newUser);

// Close the interface after processing


setTimeout(() => rl.close(), 3000); // Allow time for all events to
complete
});
});
List of most used methods
The events module is extensive, not only are we limited to being able to
emit and listen for events, but we can also manage the communication
channel, assign and remove listeners.
 eventNames: Returns an array of strings of the assigned events.
 once: Event listener that will be triggered only once.
 removeListener: Remove a specific listener.
 removeAllListeners: Remove all listeners from the event.

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

console.log('This message is displayed first.');

process.on('exit', code => {


setTimeout(() => {
console.log('Will not get displayed');
}, 8000);

console.log('Exited with status code:', code);


});
console.log('Execution Completed');

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"

Process also provides various properties to interact with. Some of them


can be used in a Node application to provide a gateway to
communicate between the Node application and any command line
interface. This is very useful if you are building a command line
application or utility using Node.js
process.stdin: a readable stream
process.stdout: a writable stream
process.stderr: a wriatable stream to recognize errors

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

createClient() Deprecated. Creates a HTTP client

createServer() Creates an HTTP server

get() Sets the method to GET, and returns an object


containing the user's request

globalAgent Returns the HTTP Agent

request() Returns an object containing the user's request

Creating an HTTP Server:


 You can create an HTTP server in Node.js using the
http.createServer() method. This method takes a callback function
as an argument, which gets called whenever a request is received by
the server.
 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.
const htt = require("http");
const server = htt.createServer((request, response)=>{
res.writeHead(200)
res.end("hello world")
})

server.listen(4000, ()=>{
console.log("Server running")
})

 We import the http module using require('http').


 We create an HTTP server using http.createServer(), passing in a
callback function that handles incoming requests.
 Inside the callback function, we use res.writeHead() to set the
HTTP status code and headers for the response.
 We then use res.end() to send the response body, which in this
case is "Hello, world!".
 Finally, we call server.listen() to make the server listen on port
3000.

var http = require('http');


var server = http.createServer(function(req, res){
//write code here
});

Http request
Example1:
const http = require('http');
// Define the host and port
const hostname = '127.0.0.1';
const port = 4000;

// Create an HTTP server


const server = http.createServer((req, res) => {
// Set the response header with status code 200 and
content type as plain text
res.writeHead(200, {'Content-Type': 'text/plain'});

// Handle different routes


if (req.url === '/hello') {
res.end('hello page>');
} else if (req.url === '/about') {
res.end('This is the about page.\n');
} else {
res.end('Node.js server!\n');
}
});

// Start the server


server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:$
{port}/`);
});

Example2:
const http = require('http');

const options = {
hostname: 'www.example.com',
port: 80,
path: '/',
method: 'GET'
};

const req = http.request(options, (res) => {


console.log(`Status code: ${res.statusCode}`);

res.on('data', (chunk) => {


console.log(`Received data: ${chunk}`);
});
});

req.on('error', (error) => {


console.error(`Error making request: ${error.message}`);
});

req.end();

Reading JSON data and Html file


Example1:
var http = require('http');

var server = http.createServer(function (req, res) {

if (req.url == '/data') {
res.writeHead(200, { 'Content-Type':
'application/json' });
res.write(JSON.stringify({ message: "Hello
World"}));
res.end();
}
});

server.listen(5000);

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


running..')

Reading JSON/HTML file/HTML data


const htt = require("http");
const fs = require("fs");

/* const obj = {
"name": "ABC",
"Age": 25
}; */
const server = htt.createServer((req, res)=>{
res.writeHead(200)
//reading json response
/* res.end(JSON.stringify(obj)) */

//reading html file


const html = fs.readFileSync("./index.html", "utf-8")
res.end(html);

/* res.end("<h1>hello world</h1>") */ //reading html data


})
server.listen(3000, ()=>{
console.log("Server running")
})

Handling GET request using GET

const http = require('http')

const fs = require('fs')

const port = 8000

const express = require('express')

const app = express()

//JSON.parse() will convert the json file into java script obj

let movie = JSON.parse(fs.readFileSync('./data/movies.json'));

//endpoit and route call back function

app.get('/api/v1/movies', (req, res)=>{

res.status(200).json(/* {

status: "sucess",

data: {

movies: movie

} */

movie

} )
app.listen(port, ()=>{

console.log('Server running')

})

HTTP methods are hypertext transfer protocol methods to exchange


data between two or more layers of an application using a request and
response cycle.
In web development, we use HTTP methods to connect client-side code
to server-side code and databases. The database for a particular
website is too large, so it is not possible to store the database on the
client side. That’s why we implement a server and setup different HTTP
routes through which we can exchange data from the client side to the
server side.
A Node.js application using ExpressJS is ideally suited for building REST
APIs. The term REST API or RESTFul API is used for a web Application
that exposes its resources to other web/mobile applications through
the Internet, by defining one or more endpoints which the client apps
can visit to perform read/write operations on the host's resources.
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.

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 list of all the


1 / GET empty
movies.

JSON Add details of new


2 / POST
String movie.

JSON Delete an existing


3 /:id DELETE
String movie.

Show details of a
4 /:id GET empty
movie.

JSON Update an existing


5 /:id PUT
String movie

Creating RESTful API for A Library


Consider we have a JSON based database of users having the following
list of movies in a file movies.json:
[{"id":1,"title":"movie1","year":"1990","rating":"7.9"},
{"id":2,"title":"movie2","year":"1991","rating":"9.0"},
{"id":3,"title":"movie3","year":"1994","rating":"7.6"},
{"id":4,"title":"movie4","year":"1950","rating":"7.9"},
{"id":5,"title":"movie5","year":"1997","rating":"6.9"},
{"id":6,"title":"mo1","year":"19","rating":"6.0"},
{"id":7,"title":"mo3","year":"1998","rating":"6.0"},
{"id":8,"title":"mo3","year":"1998","rating":"6.0"},
{"id":9,"title":"mo3","year":"1998","rating":"6.0"}]
Our API will expose the following endpoints for the clients to perform
CRUD operations on the movies.json file, which the collection of
resources on the server.

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')

const port = 8000

const express = require('express')

const app = express()

//JSON.parse() will convert the json file into java script obj

let movie = JSON.parse(fs.readFileSync('../data/movies.json'));

//endpoit and route call back function

app.get('/api/v1/movies', (req, res)=>{

res.status(200).json(movie)

} )

app.listen(port, ()=>{

console.log('Server running')

})

List SpecificMovie based on ID

const http = require('http')


const fs = require('fs')

const port = 8000

const express = require('express')

const app = express()

let movie = JSON.parse(fs.readFileSync('../data/movies.json'));

app.get('/api/v1/movies/:id', (req,res)=>{

let id = req.params.id * 1;

const find_movie = movie.find(el => el.id ===id)

res.status(200).json(find_movie)

if(!find_movie){

return res.status(404).json({

"status": "Failed",

"message":"Could not find the movie"

})

})

app.listen(port, ()=>{

console.log('Server running')

})

Add new movie to movie.json using POST method


const http = require('http')

const fs = require('fs')

const port = 8000

const express = require('express')

const app = express()

//using middleware for post method

app.use(express.json())
//JSON.parse() will convert the json file into java script obj

let movie = JSON.parse(fs.readFileSync('../data/movies.json'));

app.post('/api/v1/movies', (req, res)=>{

const newId = movie[movie.length - 1].id+1;

const newMovie = Object.assign({id:newId}, req.body)

movie.push(newMovie)

//res.status(201).json(movie)

fs.writeFile('../data/movies.json', JSON.stringify(movie), ()=>{

res.status(201).json(movie)

})

//console.log(req.body)

//res.send('created')

})

app.listen(port, ()=>{

console.log('Server running')

})

Updating movie using Put/Patch method


const http = require('http')

const fs = require('fs')

const port = 8000

const express = require('express')

const app = express()

//using middleware for req.body

app.use(express.json())

let movie = JSON.parse(fs.readFileSync('../data/movies.json'));

app.put('/api/v1/movies/:id', (req,res)=>{

let id = req.params.id * 1;
let m_update= movie.find(el => el.id===id)

let index = movie.indexOf(m_update)

const updated_movie =Object.assign(m_update, req.body)

movie[index] = updated_movie

fs.writeFile('../data/movies.json', JSON.stringify(movie), ()=>{

res.status(201).json(updated_movie)

})

})

app.listen(port, ()=>{

console.log('Server running')

})

Deleting a movie based on id


const http = require('http')

const fs = require('fs')

const port = 8000

const express = require('express')

const app = express()

app.use(express.json())

let movie = JSON.parse(fs.readFileSync('../data/movies.json'));

app.delete('/api/v1/movies/:id', (req,res)=>{

const id = parseInt(req.params.id)

const del_movie = movie.find(el=>el.id===id)

const index = movie.indexOf(del_movie)

movie.splice(index,1)

fs.writeFile('../data/movies.json', JSON.stringify(movie), ()=>{

res.status(201).json(movie)
})

if(!del_movie){

return res.status(404).json({

status: "fail",

message: "movie can not be found"

})

})

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

Model-View-Controller(MVC) architecture for Node applications


1. The client will first send a request for the Server.

2. The controller takes that request and passes it to the model.


3. The model interacts with the database, and in the process, it also
executes some business logic if required.
4. After getting the data from the database, it will pass to the controller.
5. The controller will pass the data to the view.
6. The View formats the data.
7. The format data is sent to the Client.
 MVC is simply a design or architectural pattern used in software
engineering. While this isn’t a hard rule, but this pattern helps
developers focus on a particular aspect of their application, one step
at a time.
 The main goal of MVC is to split large applications into specific
sections that have their own individual purpose.
 Model-View-Controller (MVC) is a software architectural pattern
that separates an application into three main logical components:
the model, the view, and the controller. Each of these components
are built to handle specific development aspects of an application.
 The MVC pattern is often used in the development of web
applications.

Model: The Model represents the application's data and business


logic. It defines how data is stored, retrieved, and manipulated. In a
Node.js application, the Model can include database interactions,
data validation, and any other logic related to data management.
Popular database libraries like MongoDB (with Mongoose) or
PostgreSQL (with Sequelize) are often used to work with the Model
layer in Node.js applications.

View: The View is responsible for presenting data to the user. It


handles the user interface and displays information in a way that is
understandable and visually appealing. In Node.js, the View can be
implemented using HTML templates, CSS, and client-side JavaScript
frameworks like React or Angular for building dynamic and
interactive user interfaces. Templating engines such as EJS,
Handlebars, or Pug (formerly known as Jade) are commonly used to
generate HTML dynamically and embed data from the Model into
views.
Controller: The Controller acts as an intermediary between the Model
and the View. It handles user requests, processes input, interacts with
the Model to retrieve or update data, and decides which View to
render. In Node.js, the Controller is typically implemented using server-
side code, often in the form of route handlers in a framework like
Express.js.The Controller interprets the user's actions and orchestrates
the appropriate responses, ensuring that the Model and View remain
loosely coupled.

In a Node.js application following the MVC pattern, these components


work together to create a structured and maintainable codebase. The
Model handles data-related concerns, the View deals with presentation,
and the Controller manages the flow of data and user interactions.
overview of how to connect Mongoose to a MongoDB database, how
to define a schema and a model, and how to make basic queries.
Installing Mongoose and MongoDB
Mongoose is installed in your project (package.json) like any other
dependency — using npm. To install it, use the following command
inside your project folder:
npm install mongoose
1. Connection code
Provide the MongoDB URI of your cluster to mongoose.connect()

// Import the mongoose module


const mongoose = require("mongoose");
// Define the database URL to connect to.
const connection_string = "mongodb://127.0.0.1/my_database";
async function main() {
await mongoose.connect(connection_string);
}
2. Defining and creating models
Models are defined using the Schema interface. The Schema allows you
to define the fields stored in each document along with their validation
requirements and default values. Schemas are then "compiled" into
models using the mongoose.model() method. Once you have a model
you can use it to find, create, update, and delete objects of the given
type.
Note: Each model maps to a collection of documents in the MongoDB
database. The documents will contain the fields/schema types defined
in the model Schema.
3. Defining schemas
The code fragment below shows how you might define a simple
schema. First you require() mongoose, then use the Schema
constructor to create a new schema instance, defining the various fields
inside it in the constructor's object parameter.
// Require Mongoose
const mongoose = require("mongoose");
// Define a schema
const Schema = mongoose.Schema;
const SomeModelSchema = new Schema({
name: String,
age: {type:number, required:true, default:18, min:18, max:40}
});
4. Creating a model
Models are created from schemas using the mongoose.model()
method:
// Define schema
const Schema = mongoose.Schema;
const SomeModelSchema = new Schema({
a_string: String,
a_date: Date,
});
// Compile model from schema
const SomeModel = mongoose.model("model_name",
schema_name);

const SomeModel = mongoose.model("SomeModel",


SomeModelSchema);

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

Configuring The MongoDB Node.js Connection


const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')
// Connect to database
client.connect()
.then(() => console.log('Connected Successfully'))
.catch(error => console.log('Failed to connect', error))

Insert Documents
const { MongoClient } = require('mongodb')

// Create Instance of MongoClient for mongodb


const client = new MongoClient('mongodb://localhost:27017')

// 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))

NPM COMMANDS, READLINE MODULE, PROMP-ASYNC MODULE, BUILT-IN NODEJS


MODULES, USER DEFINED MODULES IN NODEJS, IMPORTING AND EXPOTING MODULES IN
NODEJS, IMPORTING JSON FILE IN NODEJS, HTTP MODULE, FS MODULE, PATH
MODULE, READING A JSON/PLAIN/HTML FILE IN NODEJS, READING SYNCHORNOUSLY,
READING ASYNCHRONOUSLY, WRITING A JSON/PAIN/HTML FILE, OPENING A FILE,
RENAMING A FILE, APPENDING A DATA TO A FILE, DELETING A FILE IN NODEJS,
NODEJS TIMERS, SETINTERVAL() TIMER, SETIMMEDIATE() TIMER, SETTIMEOUT()
TIMER, CLEARING THESE TIMERS IN NODEJS, NODEJS EVENTS, CUSTOM EVENTS,
EVENTEMITTER CLASS, HANDLING CUSTOM EVENT ONLY ONCE, ERROR HANDLING IN
NODEJS, NODEJS PROCESS AND ITS METHODS, CRATING HTTP SERVER USING EXPRESS
AND WITHOUT USING EXPRESS, HTTP METHODS, RESPONSE AND REQUEST PARAMETER,
HANDLING DIFFERENT ROUTES IN NODEJS, GET, POST, PUT, PATCH, DELETE METHODS
OF HTTP MODULE IN NODEJS, EXPRESSJS, EXPREJS WITH MONGODB

You might also like