Download as pdf or txt
Download as pdf or txt
You are on page 1of 66

Node.

js
Chapter 5
Basics of Node.js
● Node.js is a cross-platform runtime environment and library for running
JavaScript applications outside the browser.
● It is used for creating server-side and networking web applications.
● It is open source and free to use. It can be downloaded from this link
https://nodejs.org/en/
Features of Node.js
Following is a list of some important features of Node.js that makes it the first choice of
software architects.
● Extremely fast: Node.js is built on Google Chrome's V8 JavaScript Engine, so its
library is very fast in code execution.
● 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.
Features of Node.js
● Highly Scalable: Node.js is highly scalable because event mechanism helps the
server to respond in a non-blocking way.
● 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.
● Open source: Node.js has an open source community which has produced many
excellent modules to add additional capabilities to Node.js applications.
● License: Node.js is released under the MIT license.
A Simple Node.js application

Output
Creating a Node.js Web Server

● require() is used to
consume modules.

● It allows you to include


modules in your app.

● You can add built-in core


Node.js modules and local
modules .
Express JS
● ExpressJS is a free and open-source web application framework that is built on top of
Node.js.

● It’s designed to simplify the process of building and maintaining server-side


applications.
● With ExpressJS, you can create dynamic and interactive websites, build RESTful
APIs, and handle HTTP requests and responses in an organized and efficient manner.
Render a static file with Node.js and express
Create a folder called views in the root directory to put your files that are going to
be rendered. Then, create the HTML file that you want to render. Here I’ve put
index.html file in the root directory of the application.
Render a static file with Node.js and express
Render a static file with Node.js and express
● The Path Module in Node.js
provides the utilities for
working with file and
directory paths.

● The express.static()
function is a built-in
middleware function in
Express. It serves static
files.

● The __dirname in a node


script returns the path of
the folder where the current
JavaScript file resides.
Render a static file with Node.js and express
Render a dynamic file
There are several templates such as pug, handlebars, ejs, etc to render dynamic
web pages. But we are going to use handlebars for our project.
Render a dynamic file
Render a dynamic file
Template Engine
Template engine helps us to create an HTML template with minimal code. Also, it
can inject data into HTML template at client side and produce the final HTML.
Template Engine Working
Template Engine
● As per the above figure, client-side browser loads HTML template,
JSON/XML data and template engine library from the server.
● Template engine produces the final HTML using template and data in client's
browser.
● However, some HTML templates process data and generate final HTML page
at server side also.
● There are many template engines available for Node.js. Each template engine
uses a different language to define HTML template and inject data into it.
Template Engine
The following is a list of important (but not limited) template engines for Node.js

Jade Nunjucks
Vash Handlebars
EJS atpl
Mustache haml
Dust.js
Advantages of Template engine in Node.js
● Improves developer's productivity.
● Improves readability and maintainability.
● Faster performance.
● Maximizes client side processing.
● Single template for multiple pages.
Handlebars
● Handlebars is a simple templating language.
● It uses a template and an input object to generate HTML or other text
formats. Handlebars templates look like regular text with embedded
Handlebars expressions.

A handlebars expression is a {{, some contents, followed by a }}. When the template is executed,
these expressions are replaced with values from an input object.

Installation : Type in npm install hbs in the terminal


Handlebars

Accessing Nested
Input Objects
Dynamic Routes
● To use the dynamic routes, we should provide different types of routes.
● Using dynamic routes allows us to pass parameters and process based on
them.
Dynamic Routes
Dynamic Routes
Dynamic Routes
Dynamic Routes
Session Tracking
● We can use Node.js with Express to manage sessions. A website uses HTTP protocol to
transfer information between a client and a server.

● This HTTP protocol is a stateless protocol, where the server won’t have a status of
communication and it doesn’t keep track of requests and responses made from a client to the
server.

● In terms of security, it is really better to track the user request to know how many times a
user requests or which data a user wants to access, etc.

● To make the HTTP protocol stateful from stateless, we have sessions.


Session Tracking
When a client makes an HTTP request, and that request doesn't contain a session cookie,
a new session will be created by express-session. Creating a new session does a few
things:

● generate a unique session id


● store that session id in a session cookie (so subsequent requests made by the client
can be identified)
● create an empty session object, as req.session

depending on the value of saveUninitialized, at the end of the request, the session object
will be stored in the session store .
Session Tracking
Express-session -> an HTTP server-side framework used to create and manage a session

You can install the same using npm install express-session

Session arguments

secret - This is the secret used to sign the session ID cookie. Using a secret that cannot be guessed will
reduce the ability to hijack a session to only guessing the session ID.

resave - Forces the session to be saved back to the session store, even if the session was never modified
during the request.

saveUninitialized - If during the lifetime of the request the session object isn't modified then, at the end
of the request and when saveUninitialized is false, the (still empty, because unmodified) session object will
not be stored in the session store.
Session Tracking
Session Tracking
Validation
Express Validator is an Express middleware library that you can incorporate in your
apps for server-side data validation.

Why Server-Side Validation?

Mainly speaking, you must care about server-side validation because data coming from
other clients (single-page apps, regular web apps, mobile applications, etc.) cannot be
trusted.

For example, your servers have no means to know if a malicious user (or virus) disabled
front-end validation (e.g., JavaScript) to allow the app to submit bogus data to your
server. That is, client-side validation is not enough.
Validation
● ValidationResult : Extracts the validation errors from a request and makes them
available in a Resultant object.
● We require the check and validationResult objects from the package:

const { check, validationResult } = require('express-validator');

● Every check() call accepts the parameter name as argument. Then we call
validationResult() to verify there were no validation errors.
Validation
Steps to work with express-validator module:

1) You can install this package by using this command.

npm install express-validator


Validation

sampleform.html
Validation
Validation
Validation
Validation
Other methods of Express Validator
Other methods of Express Validator
Other methods of Express Validator
Other methods of Express Validator
You can validate the input against a regular expression using matches().

Dates can be checked using

● isAfter(), check if the entered date is after the one you pass
● isBefore(), check if the entered date is before the one you pass
Error Handling
● There are two types of errors, programmer and operational.
● We use the phrase “error” to describe both, but they are quite different in
reality because of their root causes.
Programmer errors
Programmer errors depict issues with the program written — bugs. In other words,
these are the errors caused by the programmer’s mistakes while writing a program.

● Array index out of bounds — trying to access the seventh element of the array when
only six are available
● Syntax errors — failing to close the curly braces while defining a JavaScript function
● Reference errors — accessing a function or variables that are not defined
● Type error — x object is not iterable
● Failing to handle operational error
Operational errors
Every program faces operational errors (even if the program is correct). These are issues
during runtime due to external factors that can interrupt the program’s
normal flow.

These are some examples:


● Unable to connect server/database
● Request timeout
● Invalid input from the user
● 500 response from a server
● File not found
Error handling techniques
To handle the errors effectively, we need to understand the error delivery
techniques.

Few of the available fundamental strategies to report errors in Node.js are

● try…catch blocks

● Callbacks
try…catch blocks
In the try…catch method, the try block surrounds the code where the error can
occur. In other words, we wrap the code for which we want to check errors; the
catch block handles exceptions in this block.
try…catch blocks

Assuming the file is not


present the following
error is thrown
Callbacks
● A callback function in error handling is an argument to the function in which
we implement error handling.
● The purpose of a callback function is to check the errors before the result of
the primary function is used.
● The callback is usually the final argument to the primary function, and it
executes when an error or outcome of the operation emerges.
Callbacks
Syntax for a callback function
function (err, result) {}
The first argument is for an error, and the second is for the result.

In case of an error, the first attribute will contain the error, and the second
attribute will be undefined and vice versa.
Callbacks
Callbacks
File Handling
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');
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):
Read Files
Create a Node.js file that reads the HTML file, and return the content:
Read Files
Create Files
The File System module has methods for creating new files:

● fs.appendFile()

● fs.open()
● fs.writeFile()
fs.appendFile()
The fs.appendFile() method appends specified content to a file. If the file does not exist,
the file will be created
fs.open()
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.
fs.writeFile()
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
Update Files
The File System module has methods for updating files:

fs.appendFile()

fs.writeFile()
appendFile()
The fs.appendFile() method appends the specified content at the end of the
specified file
writeFile()
The fs.writeFile() method replaces the specified file and content:

Replace the content of the file "mynewfile3.txt":


Delete Files
To delete a file with the File System module, use the fs.unlink() method.

The fs.unlink() method deletes the specified file:


Rename Files
To rename a file with the File System module, use the fs.rename() method.

The fs.rename() method renames the specified file:

Rename "mynewfile1.txt" to "myrenamedfile.txt":

You might also like