Professional Documents
Culture Documents
Unit 5 - Part II
Unit 5 - Part II
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.
● The express.static()
function is a built-in
middleware function in
Express. It serves static
files.
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.
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.
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
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.
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:
● 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:
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().
● 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.
● 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
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.
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: