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

Introduction to NodeJS and Expressupdated

Uploaded by

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

Introduction to NodeJS and Expressupdated

Uploaded by

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

BACK END TECHNOLOGIES

23CAH-705
BOOKS
 Learning Node.js Development Andrew Mead 1st edition Pockt
2018
 Node.js in Action Tim Oxley, Nathan Rajlich, TJ Holowaychuk,
Alex Yo,1, Manning 2017
 Professional Node.js Pedro Teixeira 1 Wiley 2012
 Practical Node.Js: Building Real-World Scalable Web Apps by
Azat Mardan second edition Aprex 2022
COURSE OUTCOMES
CO1 Understand the architecture and design principles of back-end
systems, including APIs, web services, and serverless computing

CO2 Apply the knowledge and skills acquired to develop and deploy back-
end applications, using tools such as Node.js
CO3 Understand the working of Git to upload the created project

CO4 Apply the CRUD operations of MongoDB in the development of


website
CO5 Analyse about the express architecture for creating backend server
INTRODUCTION TO
NODEJS AND EXPRESS
INTRODUCTION TO FULL-STACK
DEVELOPMENT
 Full Stack Development refers to the development of the
web application’s both front end(client side) and back
end(server side) portions.
 Full stack development is the process of designing,
creating, testing, and deploying a complete web
application from start to finish.
FULL-STACK WEB DEVELOPERS
Full-stack web developers have the ability to design complete web
applications and websites. They work on the frontend, backend,
database, and debugging of web applications or websites.
FRONT-END DEVELOPMENT

 Client software, also known as a front end.


 It is the visible part of a website or web application which
is responsible for user experience.
 The user directly interacts with the front-end portion of the
web application or website.
FRONT-END TECHNOLOGIES
• HTML
• CSS
• JavaScript
FRONT-END LIBRARIES AND FRAMEWORKS

• AngularJS (Framework perfect for Single Page Applications)


 React.js (Library created by Facebook, User Interface (UI) library, a
tool for building UI components)
• Bootstrap (CSS Framework open-source front-end development, to
enable responsive development of mobile-first websites, collection
of template designs)
• Vue (JS Framework for building user interfaces)
• Lodash (JS Library, arrays, strings, Objects, Map, filters, etc.
functionalities)
FRONT-END LIBRARIES AND FRAMEWORKS
• Moment.js (JavaScript library helps in parsing, validating,
manipulating, and displaying date/time)
• Axios (JavaScript library used to make HTTP requests)
• jQuery (JavaScript library that simplifies the interactions between
an HTML/CSS document, or more precisely the Document Object
Model (DOM), and JavaScript)
• SASS (Syntactically Awesome Style Sheets is the most reliable,
mature, and robust CSS extension language to style HTML
elements)
BACK-END TECHNOLOGIES
 anything used on the server-side to build stable and efficient
web architectures
 responsible for managing the database through queries and
APIs by client-side commands.
BACK-END TECHNOLOGIES
• PHP (server-side scripting language designed specifically for web
development)
• C++ (general-purpose programming language)
• Java (one of the most popular and widely used programming
languages and platforms)
• Python (a programming language that lets you work quickly and
integrate systems more efficiently)
• Node.js (an open-source and cross-platform runtime environment
for executing JavaScript code outside of a browser. NodeJS is not a
framework and it’s not a programming language, used in production
by large companies such as Paypal, Uber, Netflix, Walmart, etc.)
BACK END FRAMEWORKS
• Express (node js web application framework that provides broad
features for building a single page, multipage, and hybrid web
application)
• Django (high-level Python web framework that enables rapid
development of secure and maintainable websites)
• Rails (a framework for web application development written in
Ruby)
• Laravel (easy-to-use web framework that will help you create
extensible PHP-based websites and apps)
• Spring (an open-source application Java EE framework that provides
infrastructure support for developing Java applications)
DATABASE
is the collection of inter-related data that helps in the efficient
retrieval, insertion, and deletion.
 Oracle (the collection of data that is treated as a unit. The purpose of
this database is to store and retrieve information related to the query.
It is a database server and is used to manage information).
• MongoDB (the most popular NoSQL database, is an open-source
document-oriented database)
• SQL (Structured Query Language, a standard Database language
that is used to create, maintain and retrieve the relational database)
POPULAR STACKS

• MEAN Stack (MongoDB, Express, AngularJS and


Node.js)
• MERN Stack (MongoDB, Express, ReactJS and Node.js)
• Django Stack (Django, python, and MySQL as Database)
• Rails or Ruby on Rails (Ruby, PHP, and MySQL.
• LAMP Stack (Linux, Apache, MySQL, and PHP)
MEAN STACK
It is a JavaScript-based framework for developing web
applications. MEAN is named
after MongoDB, Express, Angular, and Node, the four key
technologies that make up the layers of the stack.
• MongoDB — document database
• Express(.js) — Node.js web framework
• Angular(.js) — a client-side JavaScript framework
• Node(.js) — the premier JavaScript web server
MEAN STACK ARCHITECTURE
The MEAN architecture is designed to make building web
applications in JavaScript and handling JSON incredibly easy
MEAN STACK ADVANTAGES

• Suited for real-time applications, News aggregation sites, calendar


applications, and Interactive forums
 All of the MEAN stack components are open-source in nature
 The E and A of MEAN (Express and Angular) are two of the most
popular and well-supported JavaScript frameworks.
 Express makes routing and managing HTTP requests and
responses super easy, and includes great support for middleware to
handle JSON endpoints.
 Angular is a powerful tool for building dynamic HTML pages that
communicate with a back-end server.
MEAN STACK DISADVANTAGES

 Concurrency and performance problems at scale due to JavaScript


nature.
 Additionally, since the development opportunity is so rapid,
business and server logic might suffer from poor isolation, making
potential spaghetti code and bad practices a reality along the way.
 Finally, although there are many guides and tutorials out there,
they generally will not include concrete JS coding guidelines
appropriate for this stack.
MERN STACK
MERN Stack is a JavaScript Stack that is used for easier
and faster deployment of full-stack web applications.
MERN Stack comprises 4 technologies namely:
 MongoDB — document database
• Express(.js) — Node.js web framework
• React(.js) — a client-side JavaScript framework
• Node(.js)— the premier JavaScript web server

Express and Node make up the middle (application) tier. Express.js is a


server-side web framework, and Node.js is a popular and powerful
JavaScript server platform.
MERN STACK ARCHITECTURE
The MERN architecture is designed to make building web
applications in JavaScript and handling JSON incredibly easy
MERN STACK ADVANTAGES
• MongoDB works extremely well with Node.js and makes storing,
manipulating, and representing JSON data at every tier of your
application incredibly easy.
• Express.js (running on Node.js) and React.js make the
JavaScript/JSON application MERN full stack, well, full.
• Express.js is a server-side application framework that wraps HTTP
requests and responses and makes it easy to map URLs to server-
side functions.
• React.js is a front-end JavaScript framework for building
interactive user interfaces in HTML and communicating with a
remote server.
INTRODUCTION TO NODEJS

• Node.js is a cross-platform environment and library for running


JavaScript applications outside the browser which is used to create
networking and server-side applications
• Node.js is free
• Node.js runs on various platforms (Windows, Linux, Unix, Mac OS
X, etc.)
• Node.js uses JavaScript on the server
• Node.js = Runtime Environment + JavaScript Library
NODEJS INSTALLATION ON LINUX

Open Terminal window(ctrl+alt+t)

Type command sudo apt-get install python-software-properties

Type command sudo apt-add-repository ppa:chris-lea/node.js

Type command sudo apt-get update

Type command sudo apt-get install nodejs npm

Type command sudo apt-get install nodejs

To check the version installed Type the command node –version

Type the command npm -v to check the version of the node package manager
NODEJS INSTALLATION ON WINDOW
 Download Node.js
The official Node.js website has installation instructions for Node.js:
https://nodejs.org
WHY NODE.JS?
Node.js uses asynchronous programming!
 A common task for a web server can be to open a file on the
server and return the content to the client.
 Here is how PHP or ASP handles a file request:
1.Sends the task to the computer's file system.
2.Waits while the file system opens and reads the file.
3.Returns the content to the client.
4.Ready to handle the next request.
Here is how Node.js handles a file request:
1.Sends the task to the computer's file system.
2.Ready to handle the next request.
3.When the file system has opened and read the file, the server
returns the content to the client.
 Node.js eliminates the waiting and simply continues with the
next request.
 Node.js runs single-threaded, non-blocking, asynchronous
programming, which is very memory efficient.
WHAT CAN NODE.JS DO?

• Node.js can generate dynamic page content


• Node.js can create, open, read, write, delete, and close files
on the server
• Node.js can collect form data
• Node.js can add, delete, and modify data in your database
WHAT IS A NODE.JS FILE?

• Node.js files contain tasks that will be executed on certain events


• A typical event is someone trying to access a port on the server
• Node.js files must be initiated on the server before having any effect
• Node.js files have the extension ".js"
First Node Js Program
var http = require('http');

http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);

Save the file on your computer: C:\Users\Your Name\myfirst.js. The code


tells the computer to write "Hello World!" if anyone (e.g. a web browser)
tries to access your computer on port 8080.
COMMAND LINE INTERFACE
 Node.js files must be initiated in the "Command Line Interface"
program of your computer.
 How to open the command line interface on your computer depends
on the operating system. For Windows users, press the start button
and look for "Command Prompt", or simply write "cmd" in the
search field.
 Navigate to the folder that contains the file "myfirst.js", the command
line interface window should look something like this:

C:\Users\Your Name>_
 Initiate the Node.js File
 The file you have just created must be initiated by Node.js
before any action can take place.
 Start your command line interface, write node myfirst.js,
and hit enter:
 Initiate "myfirst.js":
 C:\Users\Your Name>node myfirst.js

Now, your computer works as a server!


If anyone tries to access your computer on port 8080, they will get a "Hello
World!" message in return!
Start your internet browser, and type in the address: http://localhost:8080
KEY FEATURES OF NODE.JS
KEY FEATURES OF NODE.JS
1.Asynchronous and Event-Driven: The Node.js library’s APIs are all
asynchronous (non-blocking) in nature. A server built with Node.JS
never waits for data from an API. After accessing an API, the server
moves on to the next one. In order to receive and track responses to
previous API requests, it uses a notification mechanism called Events.
2.Single-Threaded: Node.js employs a single-threaded architecture
with event looping, making it very scalable. In contrast to typical
servers, which create limited threads to process requests, the event
mechanism allows the node.js server to reply in a non-blocking
manner and makes it more scalable. When compared to traditional
servers like Apache HTTP Server, Node.js uses a single-threaded
program that can handle a considerably larger number of requests.
KEY FEATURES OF NODE.JS

1.Scalable: NodeJs addresses one of the most pressing concerns in


software development: scalability. Nowadays, most organizations
demand scalable software. NodeJs can also handle concurrent
requests efficiently. It has a cluster module that manages load
balancing for all CPU cores that are active. The capability of NodeJs
to partition applications horizontally is its most appealing feature.
2.Quick execution of code: Node.js makes use of the V8 JavaScript
Runtime motor, which is also used by Google Chrome.
KEY FEATURES OF NODE.JS
1.Cross-platform compatibility: NodeJS may be used on a
variety of systems, including Windows, Unix, Linux, Mac OS
X, and mobile devices. It can be paired with the appropriate
package to generate a self-sufficient executable.
2.Uses JavaScript: JavaScript is used by the Node.js library,
which is another important aspect of Node.js from the
engineer’s perspective. Most of the engineers are already
familiar with JavaScript. As a result, a designer who is familiar
with JavaScript will find that working with Node.js is much
easier.
KEY FEATURES OF NODE.JS

1.Fast data streaming: When data is transmitted in multiple streams,


processing them takes a long time. Node.js processes data at a very
fast rate. It processes and uploads a file simultaneously, thereby
saving a lot of time. As a result, NodeJs improves the overall speed
of data and video streaming.
2.No Buffering: In a Node.js application, data is never buffered.
DISADVANTAGES OF NODE.JS

1.API is not stable and keeps changing for NodeJs.


2.Code for large applications is complex due to the
asynchronous nature of NodeJs.
3.Does not have a strong library support system
APPLICATIONS OF NODE.JS

The following are some of the areas where Node.js is


proving to be an effective technology partner-
1.Single Page Applications
2.Data-Intensive Real-time Applications
3.I/O bound Applications
4.JSON APIs based Applications
5.Data Streaming Applications
NODE JS CONSOLE

Node.js console module provides a simple debugging console similar


to JavaScript console mechanism provided by web browsers.
There are three console methods that are used to write any node.js
stream:
1.console.log()-The console.log() function is used to display simple
message on console.
2.console.error()-
console.error(new Error('Hell! This is a wrong method.'));
3.console.warn()-The console.warn() function is used to display
warning message on console.
NODE.JS REPL
The term REPL stands for Read Eval Print and Loop. It
specifies a computer environment like a window console or a
Unix/Linux shell where you can enter the commands and the
system responds with an output in an interactive mode.
REPL ENVIRONMENT

The Node.js or node come bundled with REPL environment.


Each part of the REPL environment has a specific work.
 Read: It reads user's input; parse the input into JavaScript
data-structure and stores in memory.
 Eval: It takes and evaluates the data structure.
 Print: It prints the result.
 Loop: It loops the above command until user press ctrl-c
twice.
HOW TO START REPL

Mathematical expression
Example: >10+20-5
output 25
NODE.jS REPL

Using do while loop and Multiline expressions


var x = 0
undefined
> do {
... x++;
... console.log("x: " + x);
... } while ( x < 10 );
NODE.JS UNDERSCORE VARIABLE

You can also use underscore _ to get the last result .


NODE.JS REPL COMMANDS
Commands Description
ctrl + c It is used to terminate the current
command.
ctrl + c twice It terminates the node repl.
ctrl + d It terminates the node repl.
up/down keys It is used to see command history
and modify previous commands.
tab keys It specifies the list of current
command.
.help It specifies the list of all commands.
.break It is used to exit from multi-line
expressions.
.clear It is used to exit from multi-line
expressions.
NODE.JS PACKAGE MANAGER(NPM)
 Node package manager provides two main functionalities:
• it provides online repositories for node.js packages/modules which
are searchable on search.nodejs.org
• it also provides command line utility to install node.js packages, do
version management and dependency management of node.js
packages.
 the npm comes bundled with node.js installables in versions after
that v0.6.3. you can check the version by opening node.js command
prompt.
INSTALLING MODULES USING NPM
following is the syntax to install any node.js module:
npm install <module name>
let's install a famous node.js web framework called express:
>npm install express

you can use npm ls command to list down all the locally
installed modules.
open the node.js command prompt and execute "npm ls":
UNINSTALLING A MODULE

 to uninstall a node.js module, use the following


command:
npm uninstall express
SEARCHING A MODULE

"Npm search express" command is used to search express or


module.
Npm search express
NODE.JS COMMAND LINE OPTIONS

There is a wide variety of command line options in


Node.js. These options provide multiple ways to
execute scripts and other helpful run-time options.
Let's see the list of Node.js command line options :

Index Option Description


1. v, --version It is used to print node's version.
2. -h, --help It is used to print node command line options.
3. -e, --eval It evaluates the following argument as JavaScript. The modules which
"script" are predefined in the REPL can also be used in script.
4. -p, --print It is identical to -e but prints the result.
"script"
5. -c, --check Syntax check the script without executing.
WHAT IS A MODULE IN NODE.JS

• consider modules to be the same as JavaScript libraries.


• a set of functions you want to include in your application.
BUILT IN MODULES
Module Description
Assert Provides a set of assertion tests
buffer To handle binary data
child_process To run a child process
cluster To split a single Node process into multiple
processes
crypto To handle OpenSSL cryptographic functions
dgram Provides implementation of UDP datagram sockets
dns To do DNS lookups and name resolution functions
domain Deprecated. To handle unhandled errors
events To handle events
fs To handle the file system
http To make Node.js act as an HTTP server
https To make Node.js act as an HTTPS server.
net To create servers and clients
os Provides information about the operation
system
INCLUDE MODULES

To include a module, use the require() function with the name of


the module:
var http = require('http');
Now your application has access to the HTTP module, and is able
to create a server:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);
CREATE YOUR OWN MODULES

Example own
Create a module that returns the current date and time:
exports.mydatetime = function () {
return Date();
};

Use the exports keyword to make properties and methods available outside the module
file.
Save the code above in a file called "myfirstmodule.js"
INCLUDE YOUR OWN MODULE
now you can include and use the module in any of your node.js files.
example
use the module "myfirstmodule" in a node.js file:
var http = require('http');
var dt = require('./myfirstmodule');

http.createServer(function (req, res) {


res.writeHead(200, {'content-type': 'text/html'});
res.write("the date and time are currently: " + dt.mydatetime());
res.end();
}).listen(8080);
Notice that we use ./ to locate the module, that means that the module is
located in the same folder as the Node.js file.
NODE.JS HTTP MODULE

The Built-in HTTP Module


Node.js has a built-in module called HTTP, which allows Node.js
to transfer data over the Hyper Text Transfer Protocol (HTTP).
To include the HTTP module, use the require() method:
var http = require('http');
NODE.JS AS A WEB SERVER
The HTTP module can create an HTTP server that listens to server ports and
gives a response back to the client.
Use the createserver() method to create an http server:
Example
Get your own node.Js server
The function passed into
var http = require('http’); the http.createServer() method, will be executed
when someone tries to access the computer on
//Create a server object: port 8080.
http.createServer(function (req, res) {
res.Write('hello world!'); //Write a response to the client
res.End(); //end the response
}).listen(8080); //the server object listens on port 8080
ADD AN HTTP HEADER

If the response from the HTTP server is supposed to be displayed as HTML, you should
include an HTTP header with the correct content type:

Exhttpheader.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Hello World!');
res.end();
}).listen(8080);

The first argument of the res.writeHead() method is the status code, 200 means that all is OK,
the second argument is an object containing the response headers.
READ THE QUERY STRING
The function passed into the http.createServer() has a req argument that
represents the request from the client, as an object (http.IncomingMessage
object).
This object has a property called "url" which holds the part of the url that
comes after the domain name:
Exhttp_url.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(req.url);
res.end();
}).listen(8080);
SPLIT THE QUERY STRING
there are built-in modules to easily split the query string into readable parts, such as the
url module.
split the query string into readable parts:
var http = require('http');
var url = require('url');

http.createServer(function (req, res) {


res.writeHead(200, {'content-type': 'text/html'});
var q = url.parse(req.url, true).query;
var txt = q.year + " " + q.month;
res.end(txt);
}).listen(8080);
http://localhost:8080/?year=2017&month=july
will produce this result:
NODE.JS FILE SYSTEM MODULE

The Node.js file system module allows you to work with the file
system on your computer.
To include the File System module, use the require() method:
var fs = require('fs');
Common use for the File System module:
•Read files
•Create files
•Update files
•Delete files
•Rename files
READ FILES
The fs.readFile() method is used to read files on your computer.
Assume we have the following HTML file (located in the same folder as Node.js):

var http = require('http');


var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
CREATE FILES

he File System module has methods for creating new files:


•fs.appendFile()
•fs.open()
•fs.writeFile()
The fs.appendFile() method appends specified content to a file. If
the file does not exist, the file will be created:
 example
 create a new file using the appendfile() method:

 var fs = require('fs');
fs.appendfile('mynewfile1.txt', 'hello content!', function (err) {
if (err) throw err;
console.log('saved!');
});
OPENING A FILE
The fs.open() method takes a "flag" as the second argument, if the flag
is "w" for "writing", the specified file is opened for writing. If the file
does not exist, an empty file is created:

Example
Create a new, empty file using the open() method:
var fs = require('fs');
fs.open('mynewfile2.txt', 'w', function (err, file) {
if (err) throw err;
console.log('Saved!');
});
WRITE FILE

The fs.writefile() method replaces the specified file and


content if it exists. if the file does not exist, a new file,
containing the specified content, will be created:
example
create a new file using the writefile() method:
var fs = require('fs');
fs.writefile('mynewfile3.txt', 'hello content!', function (err) {
if (err) throw err;
console.log('saved!');
DELETE FILES
 to delete a file with the file system module, use the fs.unlink()
method.
 the fs.unlink() method deletes the specified file:
 example
delete "mynewfile2.txt":
var fs = require('fs');
fs.unlink('mynewfile2.txt', function (err) {
if (err) throw err;
console.log('file deleted!');
});
RENAME FILES
To rename a file with the File System module, use the fs.rename() method.
The fs.rename() method renames the specified file:

Example
Rename "mynewfile1.txt" to "myrenamedfile.txt":
var fs = require('fs');
fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (
err) {
if (err) throw err;
console.log('File Renamed!');
});
THE FORMIDABLE MODULE
there is a very good module for working with file uploads, called
"formidable".
the formidable module can be downloaded and installed using npm:
npm install formidable
after you have downloaded the formidable module, you can include the
module in any application:
var formidable = require('formidable');
UPLOAD FILES
now you are ready to make a web page in node.js that lets the user upload
files to your computer:
step 1: create an upload form
create a node.js file that writes an html form, with an upload field:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post"
enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}).listen(8080);
STEP 2: PARSE THE UPLOADED FILE

 include the formidable module to be able to parse the uploaded file once it reaches the server.
 when the file is uploaded and parsed, it gets placed on a temporary folder on your computer.
 var http = require('http');
var formidable = require('formidable');

http.createServer(function (req, res) {


if (req.url == '/fileupload') {
var form = new formidable.incomingform();
form.parse(req, function (err, fields, files) {
res.write('file uploaded');
res.end();
});
} else {
res.writeHead(200, {'content-type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-
data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
STEP 3: SAVE THE FILE

When a file is successfully uploaded to the server, it is placed on


a temporary folder.
The path to this directory can be found in the "files" object,
passed as the third argument in the parse() method's callback
function.
To move the file to the folder of your choice, use the File System
module, and rename the file:
 var http = require('http');
var formidable = require('formidable');
var fs = require('fs');

http.createserver(function (req, res) {


if (req.url == '/fileupload') {
var form = new formidable.incomingform();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.filepath;
var newpath = 'c:/users/your name/' + files.filetoupload.originalfilename;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write('file uploaded and moved!');
res.end();
});
});
} else {
res.writehead(200, {'content-type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
NODEMAILER
Nodemailer, an open source project started in 2010, is an npm module
for Node.js applications to send emails. Today, nodemailer is a de facto to send
an email in Node.js.
Highlights of Nodemailer
•It is a single module with zero dependencies
•It supports HTML Content
•Allows you to easily add attachments to messages
•Supports SMTP as default transport method; other supported transport
methods are SES, Sendmail, Stream.
•OAuth2 authentication
INSTRUCTIONS TO USE NODEMAILER
1.step1: open this link https://myaccount.google.com/security
2.step2: enable 2 factor authentication
3.click on app passwords just below the 2 factor authentication
4.from select app options select other and write your app name it
could be any name like rajanapp
5.it will generate you the password copy the password from the
popup and use the following code.
6.use that copied password in the auth password section my
password was this rkancqhzgvmzsdaqyx
const nodemailer = require('nodemailer');
let mailtransporter = nodemailer.createtransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: ' rkancqhzgvmzsdaqyx '
} });
let maildetails = {
from: '[email protected]',
to: '[email protected]',
subject: 'test mail',
text: 'node.js testing mail ‘ };
mailtransporter.sendmail(maildetails, function(err, data) {
if(err) {
console.log(err);
} else {
console.log('email sent successfully'); }
WHAT ARE STREAMS?
 streams are objects that let you read data from a source or write data
to a destination in continuous fashion. in node.js, there are four types
of streams −
• readable − stream which is used for read operation.
• writable − stream which is used for write operation.
• duplex − stream which can be used for both read and write operation.
• transform − a type of duplex stream where the output is computed
based on input.
STREAMS
 each type of stream is an eventemitter instance and throws
several events at different instance of times. for example, some
of the commonly used events are −
• data − this event is fired when there is data is available to read.
• end − this event is fired when there is no more data to read.
• error − this event is fired when there is any error receiving or
writing data.
• finish − this event is fired when all the data has been flushed to
underlying system.
READING FROM A STREAM
 create a text file named input.txt
 create a js file named exstreamread.js with the following code
var fs = require("fs");
var data = '';
// Create a readable stream
var readerStream = fs.createReadStream('input.txt');
// Set the encoding to be utf8.
readerStream.setEncoding('UTF8');
// Handle stream events --> data, end, and error
readerStream.on('data', function(chunk) {
data += chunk;
});
readerStream.on('end',function() {
console.log(data);
});
readerStream.on('error', function(err) {
console.log(err.stack);
});
console.log("Program Ended");
WRITING TO A STREAM
 var fs = require("fs");
 var data = 'simply easy learning';
 // create a writabe stream
 var writerStream = fs.createwritestream('output.txt');
 // write the data to stream with encoding to be utf8
 writerStream.write(data,'utf8');
 // mark the end of file
 writerStream.end();
 // handle stream events --> finish, and error
 writerStream.on('finish', function() {
 console.log("write completed.");
 });
PIPING THE STREAMS
 piping is a mechanism where we provide the output of
one stream as the input to another stream. it is normally
used to get data from one stream and to pass the output
of that stream to another stream. there is no limit on
piping operations. now we'll show a piping example for
reading from one file and writing it to another file.
PIPING THE STREAMS

var fs = require("fs");

// Create a readable stream


var readerStream = fs.createReadStream('input.txt');

// Create a writable stream


var writerStream = fs.createWriteStream('output.txt');

// Pipe the read and write operations


// read input.txt and write data to output.txt
readerStream.pipe(writerStream);

console.log("Program Ended");
CHAINING THE STREAMS

 chaining is a mechanism to connect the output of one stream to


another stream and create a chain of multiple stream operations. it is
normally used with piping operations. now we'll use piping and
chaining to first compress a file and then decompress the same.
var fs = require("fs");
var zlib = require('zlib');

// Compress the file input.txt to input.txt.gz


fs.createReadStream('input.txt')
.pipe(zlib.createGzip())
.pipe(fs.createWriteStream('input.txt.gz'));

console.log("File Compressed.");
DECOMPRESSING
var fs = require("fs");
var zlib = require('zlib');

// Decompress the file input.txt.gz to input.txt


fs.createReadStream('input.txt.gz')
.pipe(zlib.createGunzip())
.pipe(fs.createWriteStream('input.txt'));

console.log("File Decompressed.");
WHAT IS CALLBACK?
 callback is an asynchronous equivalent for a function. a callback
function is called at the completion of a given task. node makes
heavy use of callbacks. all the apis of node are written in such a way
that they support callbacks.
 for example, a function to read a file may start reading file and return
the control to the execution environment immediately so that the
next instruction can be executed. once file i/o is complete, it will call
the callback function while passing the callback function, the content
of the file as a parameter. so there is no blocking or wait for file i/o.
this makes node.js highly scalable, as it can process a high number
of requests without waiting for any function to return results.
BLOCKING CODE EXAMPLE

 create a text file named input.txt with the following content −


we are giving self learning content to teach the world in simple
and easy way!!!!!
create a js file named exblockcode.js with the following code −
var fs = require("fs");
var data = fs.readfilesync('input.txt');
console.log(data.tostring());
console.log("program ended");
NON-BLOCKING CODE EXAMPLE

 create a text file named input.txt with the following content.


we are giving self learning content to teach the world in simple
and easy way!!!!!
 update exnonblock.js to have the following code −
var fs = require("fs");
fs.readfile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.tostring());
});

EVENTS
Each action on the computer is called an event. in nodejs objects can
fire events. according to the official documentation of node.js, it is an
asynchronous event-driven javascript runtime. node.js has an event-
driven architecture that can perform asynchronous tasks. node.js has an
‘events’ module that emits named events that can cause corresponding
functions or callbacks to be called. functions(callbacks) listen or
subscribe to a particular event to occur and when that event triggers, all
the callbacks subscribed to that event are fired one by one in order to
which they were registered.
THE EVENTEMMITTER CLASS
All objects that emit events are instances of the EventEmitter class.
The event can be emitted or listened to an event with the help of
EventEmitter.
Syntax:
const EventEmitter=require('events’);
var eventEmitter=new EventEmitter();
EVENTEMITTER.ADDLISTENER(EVENT,
LISTENER) && EVENTEMITTER.ON(EVENT, LISTENER)

 eventemmitter.on(event, listener) and


eventemitter.addlistener(event, listener) are pretty much similar. it
adds the listener at the end of the listener’s array for the specified
event. multiple calls to the same event and listener will add the
listener multiple times and correspondingly fire multiple times. both
functions return an emitter, so calls can be chained.
EVENTEMITTER.ONCE(EVENT, LISTENER)
 it fires at most once for a particular event and will be removed
from the listeners and events array after it has listened once.
returns emitter, so calls can be chained.
CODE FOR CREATING A PROGRAM OF A
SIMPLE EVENT:
var events = require('events’);
var eventEmitter = new
events.EventEmitter(); //Create an event
handler:
var myEventHandler = function ()
{ console.log('I hear a scream!'); }
//Assign the eventhandler to an event:
eventEmitter.on('scream',
myEventHandler); //Fire the 'scream' event:
eventEmitter.emit('scream');

I hear a scream!
UTILITY MODULES
there are several utility modules available in node.js module library.
these modules are very common and are frequently used while
developing any node based application.

Node.js Utility Module: The Util module in


node.js provides access to various utility
functions.

Syntax:

const util = require('util');


Sr.No. Module Name & Description
1 OS Module Provides basic operating-system related utility functions.

2 Path Module Provides utilities for handling and transforming file paths.

3 Net Module Provides both servers and clients as streams. Acts as a network
wrapper.

4 DNS Module Provides functions to do actual DNS lookup as well as to use


underlying operating system name resolution functionalities.

5 Domain Module Provides ways to handle multiple different I/O operations as a


single group.
NODE.JS OS

node.js os provides some essential utility functions related to the


operating system. let's see the list of functions or methods which are
generally used.
NODE.JS OS

// Require operating System module


const os = require("os");

// Display operating System type


console.log('Operating System type : ' + os.type());

// Display operating System platform


console.log('platform : ' + os.platform());

// Display total memory


console.log('total memory : ' + os.totalmem() + " bytes.");

// Display available memory


console.log('Available memory : ' + os.availmem() + " bytes.");
PATH MODULE
 the path module in node.js is used for transforming and handling
various file paths.

// Require path
const path = require('path');

// Display Resolve
console.log('resolve:' + path.resolve('paths.js'));

// Display Extension
console.log('extension:' + path.extname('paths.js'));
DNS MODULE
 dns module enables us to use the underlying operating system name
resolution functionalities. the actual dns lookup is also performed by the
dns module. this dns module provides an asynchronous network wrapper.
the dns module can be imported using the below syntax.
// Require dns module
const dns = require('dns');
// Store the web address
const website = 'www.cuchd.in
// Call lookup function of DNS
dns.lookup(website, (err, address, family) => {
console.log('Address of %s is %j family: IPv%s’, website, address,
family);
});
NET MODULE
net module in node.js is used for the creation of both client and server.
similar to dns module this module also provides an asynchronous network
wrapper.
// Require net module
const net = require('net');
const server = net.createServer(function (connection) {
console.log('client connected'); connection.on('end', function () {
console.log('client disconnected');
});
connection.write('Hello World!\r\n'); connection.pipe(connection);
});
server.listen(8080, function () {
console.log('server listening');
});
const net = require('net');
const client = net.connect(8124, function () {
console.log('Client Connected');
client.write(‘Chandigarh University\r\n');
});
client.on('data', function (data) {
console.log(data.toString());
client.end();
});
client.on('end', function () {
console.log('Server Disconnected');
});
DOMAIN MODULE:

the domain module in node.js is used to intercept unhandled errors.


the interception can be performed by either:
• internal binding: error emitter executes the code internally
within the run method of a domain.
• external binding: error emitter is added explicitly to the domain
using the add method.
Syntax:
const domain = require('domain’);

The domain class in the domain module provides a mechanism for routing
the unhandled exceptions and errors to the active domain object. It is
considered to be the child class of EventEmitter.

Syntax:
const domain = require('domain’);
const child = domain.create();
const EventEmitter = require("events").EventEmitter;
const domain = require("domain");
const emit_a = new EventEmitter();
const dom_a = domain.create();
dom_a.on('error', function (err) {
console.log("Error handled by dom_a (" + err.message + ")");
});
dom_a.add(emit_a);
emit_a.on('error', function (err) {
console.log("listener handled this error (" + err.message + ")");
});
emit_a.emit('error', new Error('Listener handles this'));
emit_a.removeAllListeners('error');
emit_a.emit('error', new Error('Dom_a handles this'));
const dom_b = domain.create();
dom_b.on('error', function (err) {
console.log("Error handled by dom_b (" + err.message + ")");
});
dom_b.run(function () {
const emit_b = new EventEmitter();
emit_b.emit('error', new Error('Dom_b handles this'));
});
dom_a.remove(emit_a);
emit_a.emit('error', new Error('Exception message...!'));

You might also like