0% found this document useful (0 votes)
19 views53 pages

Node.js Overview and Key Features

Node js notes

Uploaded by

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

Node.js Overview and Key Features

Node js notes

Uploaded by

akshay jondhale
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NODE + EXPRESS

What is Nodejs
[Link] is a JavaScript runtime built on Chrome's V8 JavaScript engine.
[Link] allows you to run JavaScript on the server.
[Link] also provides library of various JavaScript modules which helps to develop web
applications.
[Link] was developed by Ryan Dahl in 2009.
Node js is not a language or a framework.

Advantages of NodeJS
● Open Source
● Efficient, Fast and Highly Scalable
● Event Driven
● Very Popular

Prerequisite
● JavaScript
● NPM

REPL
The repl module provides a Read-Eval-Print-Loop (REPL) implementation that is available both
as a standalone program or includible in other applications.
JavaScript Expression
Variable
Global and Local Scope
_ (underscore) Variable
Function

Some Commands
.break Sometimes you get stuck, this gets you out
.clear Alias for .break
.editor Enter editor mode (Ctrl+D to finish, Ctrl+C to cancel).
.exit Exit the REPL
.help Print this help message
.load Load JS from a file into the REPL session e.g. .load ./file/to/[Link]
.save Save all evaluated commands in this REPL session to a file e.g. .save ./file/to/[Link]
Press Ctrl+C to abort current expression, Ctrl+D to exit the REPL
Run in Node JS
[Link]
[Link](“Hello Sonam”)
node [Link]

Module Wrapper
Before a module's code is executed, [Link] will wrap it with a function wrapper that looks like
the following:
(function(exports, require, module, __filename, __dirname) {
// Module code actually lives in here
});
By doing this, [Link] achieves a few things:
•It keeps top-level variables (defined with var, const or let) scoped to the module rather than the
global object.
•It helps to provide some global-looking variables that are actually specific to the module, such
as:
•The module and exports objects that the implementor can use to export values from the
module.
•The convenience variables __filename and __dirname, containing the module's absolute
filename and directory path.
exports – A reference to the [Link] that is shorter to type.
require – Used to import modules.
module – A reference to the current module.
__dirname – The directory name of the current module. This is the same as the [Link]()
of the __filename.
Example:- [Link](__dirname);
__filename – The file name of the current module. This is the current module file's absolute path
with symlinks resolved.
Example:- [Link](__filename);

Path
The path module provides utilities for working with file and directory paths. It can be accessed
using:
const path = require('path’);
basename() – The basename() method returns the last portion of a path, similar to the Unix
basename command. Trailing directory separators are ignored.
Syntax:- basename(path[, ext])
Example:- basename(‘/test/[Link]’, ‘.html’);
dirname() – The dirname() method returns the directory name of a path, similar to the Unix
dirname command. Trailing directory separators are ignored.
Syntax:- dirname(path)
Example:- dirname(‘/test/[Link]’);
extname() - The extname() method returns the extension of the path, from the last occurrence of
the . (period) character to end of string in the last portion of the path. If there is no . in the last
portion of the path, or if there are no . characters other than the first character of the basename
of path, an empty string is returned.
Syntax:- extname(path)
Example:- extname('[Link]’);
join() – The join() method joins all given path segments together using the platform-specific
separator as a delimiter, then normalizes the resulting path.
Zero-length path segments are ignored. If the joined path string is a zero-length string then '.'
will be returned, representing the current working directory.
Syntax:- join([…paths])
Example:- join('/search', 'label', 'course/python', 'oop', '..');
normalize() – The normalize() method normalizes the given path, resolving '..' and '.' segments.
If the path is a zero-length string, '.' is returned, representing the current working directory.
Syntax:- normalize(path)
Example:-
normalize('C:\\temp\\\\foo\\bar\\..\\’);
[Link]('C:////temp\\\\/\\/\\/foo/bar’);
Note - win32 property provides access to Windows-specific implementations of the path
methods.
parse() – The parse() method returns an object whose properties represent significant elements
of the path. Trailing directory separators are ignored.
Syntax:- parse(path)
Example:- parse('C:\\path\\dir\\[Link]');
isAbsolute() – The [Link]() method determines if path is an absolute path. If the given
path is a zero-length string, false will be returned.
Syntax:- isAbsolute(path)
Example:-
isAbsolute('//server'); // true
isAbsolute('\\\\server'); // true
isAbsolute('C:/foo/..'); // true
isAbsolute('C:\\foo\\..'); // true
isAbsolute('bar\\baz'); // false
isAbsolute('bar/baz'); // false
isAbsolute('.'); // false

File System
The fs module enables interacting with the file system in a way modeled on standard POSIX
functions.
Promise Based API
•const fs = require('fs/promises’);
•import * as fs from 'fs/promises';
Callback API
•const fs = require('fs’);
•import * as fs from 'fs';
Sync API
•const fs = require('fs’);
•import * as fs from 'fs';

Promise API
The fs/promises API provides asynchronous file system methods that return promises.
mkdir() – Asynchronously creates a directory.
Syntax:- mkdir(path[, options])
readdir() – Reads the contents of a directory.
Syntax:- readdir(path[, options])
rmdir() – Removes the directory identified by path.
Syntax:- rmdir(path[, options])
writeFile() – Asynchronously writes data to a file, replacing the file if it already exists.
Syntax:- writeFile(file, data[, options])
readFile() – Asynchronously reads the entire contents of a file.
Syntax:- readFile(path[, options])
appendFile(path, data[, options]) – Asynchronously append data to a file, creating the file if it
does not yet exist.
Syntax:- appendFile(path, data[, options])
copyFile() – Asynchronously copies src to dest. By default, dest is overwritten if it already exists.
Syntax:- copyFile(src, dest[, mode])
stat() – Used to get file information.
Syntax:- stat(path[, options])
Callback API
The callback APIs perform all operations asynchronously, without blocking the event loop, then
invoke a callback function upon completion or error.
mkdir() – Asynchronously creates a directory.
Syntax:- mkdir(path[, options], callback)
readdir() – Reads the contents of a directory.
Syntax:- readdir(path[, options], callback)
rmdir() – Removes the directory identified by path.
Syntax:- rmdir(path[, options], callback)
writeFile() – Asynchronously writes data to a file, replacing the file if it already exists.
Syntax:- writeFile(file, data[, options], callback)
readFile() – Asynchronously reads the entire contents of a file.
Syntax:- readFile(path[, options], callback)
appendFile(path, data[, options]) – Asynchronously append data to a file, creating the file if it
does not yet exist.
Syntax:- appendFile(path, data[, options], callback)
copyFile() – Asynchronously copies src to dest. By default, dest is overwritten if it already exists.
Syntax:- copyFile(src, dest[, mode], callback)
stat() – Used to get file information.
Syntax:- stat(path[, options], callback)

Synchronous API
The synchronous APIs perform all operations synchronously, blocking the event loop until the
operation completes or fails.
mkdirSync() – Synchronously creates a directory.
Syntax:- mkdirSync(path[, options])
readdirSync() – Reads the contents of a directory.
Syntax:- readdirSync(path[, options])
rmdirSync() – Removes the directory identified by path.
Syntax:- rmdirSync(path[, options])
writeFileSync() – Synchronously writes data to a file, replacing the file if it already exists.
Syntax:- writeFileSync(file, data[, options])
readFileSync() – Synchronously reads the entire contents of a file.
Syntax:- readFileSync(path[, options])
appendFileSync(path, data[, options]) – Synchronously append data to a file, creating the file if it
does not yet exist.
Syntax:- appendFileSync(path, data[, options])
copyFileSync() – Synchronously copies src to dest. By default, dest is overwritten if it already
exists.
Syntax:- copyFileSync(src, dest[, mode])
statSync() – Used to get file information.
Syntax:- statSync(path[, options])

OS
The os module provides operating system-related utility methods and properties.
const os = require('os’);
import * as os from ‘os’;
platform() – Returns a string identifying the operating system platform. The value is set at
compile time. Possible values are 'aix', 'darwin', 'freebsd', 'linux', 'openbsd', 'sunos', and 'win32'.
arch() – Returns the operating system CPU architecture for which the [Link] binary was
compiled. Possible values are 'arm', 'arm64', 'ia32', 'mips', 'mipsel', 'ppc', 'ppc64', 's390', 's390x',
'x32', and 'x64’.
cpus() – Returns an array of objects containing information about each logical CPU core.
hostname() – Returns the host name of the operating system as a string.
homedir() – Returns the string path of the current user's home directory.
networkInterfaces() - Returns an object containing network interfaces that have been assigned a
network address.
freemem() – Returns the amount of free system memory in bytes as an integer.
totalmem() – Returns the total amount of system memory in bytes as an integer.

URL
The url module provides utilities for URL resolution and parsing.
const url = require(‘url’);
import url from ‘url’;
const myURL = new URL('[Link]
hash – Gets and sets the fragment portion of the URL.
host – Gets and sets the host portion of the URL.
hostname – Gets and sets the host name portion of the URL. The key difference between
[Link] and [Link] is that [Link] does not include the port.
href – Gets and sets the serialized URL.
pathname – Gets and sets the path portion of the URL.
port – Gets and sets the port portion of the URL.
protocol – Gets and sets the protocol portion of the URL.
search – Gets and sets the serialized query portion of the URL.
toString() – The toString() method on the URL object returns the serialized URL. The value
returned is equivalent to that of [Link] and [Link]().
toJSON() – The toJSON() method on the URL object returns the serialized URL. The value
returned is equivalent to that of [Link] and [Link]().

Event
const EventEmitter = require('events’);
import EventEmitter from ‘events’;
on – When a listener is registered using the on() method, that listener is invoked every time the
named event is emitted. on() method is used to register listeners.
Syntax:- on(eventName, callback)
once - When a listener is registered using the once() method, it is possible to register a listener
that is called at most once for a particular event. Once the event is emitted, the listener is
unregistered and then called.
Syntax:- once(eventName, callback)
emit() – The emit() method allows an arbitrary set of arguments to be passed to the listener
functions. emit() method is used to trigger the event.
Syntax:- emit(eventName, args)

HTTP
The HTTP interfaces in [Link] are designed to support many features of the protocol which
have been traditionally difficult to use.
const http = require(‘http’);
import http from ‘http’;
createServer([options][, requestListener]) – Returns a new instance of [Link].

DNS
The HTTP interfaces in [Link] are designed to support many features of the protocol which
have been traditionally difficult to use.
const http = require(‘http’);
import http from ‘http’;
createServer([options][, requestListener]) – Returns a new instance of [Link].

Introduction to Express JS
Express Js is Fast, unopinionated, minimalist web framework for [Link].
● Create Static, Dynamic and Hybrid Web App
● Fast and Easy
● Routing
● Middleware
● REST API
● Very Popular

Prerequisite
● HTML
● CSS
● JavaScript
● NPM
● Node JS
● Bootstrap
● Tailwind CSS
● Axios
● Fetch API

Requirement for installing Express JS

● Node JS
● NPM

Installing & Uninstalling Express JS

● Install Express JS
npm install express
npm install express@5.0.0-alpha.8
● Uninstall Express JS
npm uninstall express
npm uninstall express@5.0.0-alpha.8
● Install Nodemon
npm install nodemon

Babel
Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards
compatible version of JavaScript in current and older browsers or environments. Here are the
main things Babel can do for you:
● Transform syntax
● Polyfill features that are missing in your target environment
● Source code transformations
@babel/core – This is the main package to run any babel setup or configuration.
@babel/cli – Babel comes with a built-in CLI which can be used to compile files from the
command line.
@babel/node – This is a CLI that works exactly the same as the [Link] CLI, with the added
benefit of compiling with Babel presets and plugins before running it.
@babel/preset-env – This enables us to use new and upcoming features which [Link] is yet to
understand. New features are always new and will probably take time to implement in NodeJS
by default.
npm install –D @babel/core @babel/cli @babel/node @babel/preset-env

Babel CLI

Compile Files:
● npx babel [Link] – It complies [Link] file.
● npx babel [Link] --out-file [Link] – It compiles [Link] file and output to a
file [Link]. We can use --out-file or -o
● npx babel [Link] --watch --out-file [Link] – It complies [Link] every time
we make changes and output to a file [Link]. We can use --watch or -w
Compile Directory:
● npx babel src --out-dir prd – It compiles the entire src directory and output it to the prd
directory by using either --out-dir or -d. This doesn't overwrite any other files or
directories in prd.
● npx babel src --out-file [Link] – It compiles the entire src directory and output
it as a single concatenated file.

Setup Babel

● Install All Required Babel Packages


npm install –D @babel/core @babel/cli @babel/preset-env
● Create a file called .babelrc at the root directory of Project
{ “presets”: [ “@babel/preset-env” ] } // "@babel/env"
● Open [Link] file
"scripts": {
"build": "babel [Link] --out-file prd",
"start": "npm run build && nodemon prd/[Link]“,
"serve": "node prd/[Link]"
}
● Open [Link] file
"scripts": {
"build": "babel [Link] --out-file prd",
"start": "npm run build && nodemon prd/[Link]“,
"serve": "node prd/[Link]"
}
● Open [Link] file
"scripts": {
"build": "babel src --out-dir prd",
"start": "npm run build && nodemon prd/[Link]“,
"serve": "node prd/[Link]"
}

Express Application Generator

Use the application generator tool, express-generator, to quickly create an application skeleton.
npx express-generator --view=ejs myapp
npm install -g express-generator
express --view=ejs myapp
npm install
set DEBUG=myapp:* & npm start
● myapp – Application/Project Folder
● bin – The bin folder contains the executable file that starts your app. It starts the server
(on port 3000, if no alternative is supplied) and sets up some basic error handling.
● public – Everything​in this folder is accessible to people connecting to application. We
can put JavaScript, CSS, images, and other assets.
● routes – We can put all our route files. The generator creates two files, [Link] and
[Link].
● views – The views folder is where we have files used by your templating engine.
● [Link] File – This file creates an express application object (named app, by convention),
sets up the application with various settings and middleware, and then exports the app
from the module.

First Express JS Application


// const express = require('express')
import express from 'express'
const app = express()
const port = [Link] || '3000'
[Link]('/', (req, res) => {
[Link]('Hello World!')
})
[Link](port, () => {
[Link](`Server listening at [Link]
})

express() – The express() function is a top-level function exported by the express module.
const app = express()
The app returned by express() is in fact a JavaScript Function, designed to be passed to Node’s
HTTP servers as a callback to handle requests.
This makes it easy to provide both HTTP and HTTPS versions of your app with the same code
base, as the app does not inherit from these.
[Link]() – It binds and listens for connections on the specified host and port.
If port is omitted or is 0, the operating system will assign an arbitrary unused port, which is
useful for cases like automated tasks.
Routing
Routing refers to determining how an application responds to a client request to a particular
endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so
on).
Each route can have one or more callback functions, which are executed when the route is
matched.
Syntax:- [Link](path, callback)
[Link](path, [callback1, callback2, ….])
[Link](path, [callback1, callback2, ….], callback)
● app is an instance of express.
● method is an HTTP request method, in lowercase.
● path is a path on the server.
● callback is the function executed when the route is matched.

Syntax:- [Link](path, callback)


Example:-
[Link]('/', (req, res) => {
const app = express()
[Link]('Hello World!')
[Link]('/', function (req, res) {
[Link]('Hello World!') })

}) [Link]('/', (req, res) =>{


[Link]('/', function (req, res) {
[Link]('Hello World!')
[Link]('Hello World!')
})
})

Syntax:- [Link](path, callback)


Methods
● GET – Retrieve Data
● POST – Create/Insert Data
● PUT – Completely Update Data
● PATCH – Partially Update Data
● DELETE – Delete Data
● ALL – Any HTTP Request Method
Syntax:- [Link](path, callback)
Example:-
[Link](‘/student/all', (req, res) =>{
[Link](‘All Student')
})
[Link](‘/student/create', (req, res) =>{
[Link](‘New Student Created')
})
[Link](‘/student/update’, callback)
[Link](‘/student/delete’, callback)

[Link](path, [callback1, callback2,….], callback) – This method is like the standard


[Link]() methods, except it matches all HTTP verbs.
This method is useful for mapping “global” logic for specific path prefixes or arbitrary matches.
Examples:-
[Link](‘/sabkuch’, function (req, res, next) {
[Link]('Accessing the secret section ...')
next() // pass control to the next callback
})
[Link]('*', requireAuthentication, loadUser)
[Link]('/api/*', requireAuthentication)

Syntax:- [Link](path, callback)


Path – Route paths can be strings, string patterns, or regular expressions. Query strings are not
part of the route path.
The characters ?, +, *, and () are subsets of their regular expression counterparts.
The hyphen (-) and the dot (.) are interpreted literally by string-based paths.
If you need to use the dollar character ($) in a path string, enclose it escaped within ([ and ]).
Example:-
[Link]/data/$book
[Link](“/data/([\$])book”, callback)

Syntax:- [Link](path, callback)


Callback – Route Callbacks can be in the form of a function, an array of functions, or
combinations of both.
You can provide multiple callback functions that behave like middleware to handle a request.
The only exception is that these callbacks might invoke next('route') to bypass the remaining
route callbacks.
Example:-
[Link]('/cbexample1', (req, res) => {
[Link]('One Callback Example')
})

More than one Callback Functions:-


[Link]('/cbexample2', (req, res, next) => {
[Link]('First Callback')
next()
}, (req, res) => {
[Link]('Second Callback')
[Link]('More than One Callback Example')
}
)

Why do we need Router

[Link]
// All Student Routes // All Teacher Routes

[Link](‘/student/all', (req, res) =>{ [Link](‘/teacher/all', (req, res) =>{


[Link](‘All Teachers’) })
[Link](‘All Student’) })
[Link](‘/student/create', (req, res) =>{ [Link](‘/teacher/create', (req, res) =>{
[Link](‘New Teacher Created’) })
[Link](‘New Student Created’) })
[Link](‘/student/update’, (req, res) =>{ [Link](‘/teacher/update’, (req, res) =>{
[Link](‘Teacher updated’) })
[Link](‘Student updated’) })
[Link](‘/teacher/delete’, (req, res) =>{
[Link](‘/student/delete’, (req, res) =>{ [Link](‘Teacher Deleted’) })
[Link](‘Student Deleted’) })

Router
Router class is used to create modular, mountable route handlers.
A Router instance is a complete middleware and routing system.
Every Express application has a built-in app router.
Steps:-

•Create Router Module – routes/[Link] Create/Open [Link]


•Create Router instance
Import Router Module
const router = [Link]() const stu = require(‘./[Link]’)
•Define Routes using router object
Load Router Module
[Link]('/', function (req, res) { [Link](‘/vidyarthi’, stu)

[Link](‘Hello World’)
})
•Export router
[Link] = router

routes/[Link]
routes/[Link]
const router = [Link]() const router = [Link]()
// All Teacher Routes
// All Student Routes
[Link](‘/teacher/all', (req, res) =>{
[Link](‘/student/all', (req, res) =>{
[Link](‘All Student’) }) [Link](‘All Teachers’) })

[Link](‘/student/create', (req, res) =>{ [Link](‘/teacher/create', (req, res) =>{


[Link](‘New Student Created’) })
[Link](‘New Teacher Created’) })
[Link](‘/student/update’, (req, res) =>{
[Link](‘/teacher/update’, (req, res) =>{
[Link](‘Student updated’) })
[Link](‘/student/delete’, (req, res) =>{ [Link](‘Teacher updated’) })
[Link](‘/teacher/delete’, (req, res) =>{
[Link](‘Student Deleted’) }) [Link](‘Teacher Deleted’) })
[Link] = router
[Link] = router
routes/[Link]
routes/[Link]
const router = [Link]() const router = [Link]()
// All Teacher Routes
// All Student Routes
[Link](‘/all', (req, res) =>{
[Link](‘/all', (req, res) =>{
[Link](‘All Student’) }) [Link](‘All Teachers’) })

[Link](‘/create', (req, res) =>{ [Link](‘/create', (req, res) =>{


[Link](‘New Student Created’) })
[Link](‘New Teacher Created’) })
[Link](‘/update’, (req, res) =>{
[Link](‘/update’, (req, res) =>{
[Link](‘Student updated’) }) [Link](‘Teacher updated’) })
[Link](‘/delete’, (req, res) =>{ [Link](‘/delete’, (req, res) =>{
[Link](‘Teacher Deleted’) })
[Link](‘Student Deleted’) })
[Link] = router
[Link] = router

/student/all
[Link] /student/create
const student = require(‘./students’) /student/update
/student/delete
const teacher = require(‘./teachers’)
/teacher/all
[Link](‘/student’, student)
/teacher/create
[Link](‘/teacher’, teacher) /teacher/update
/teacher/delete

Route Parameter
Route parameters are named URL segments that are used to capture the values specified at
their position in the URL.
The captured values are populated in the [Link] object, with the name of the route
parameter specified in the path as their respective keys.
The name of route parameters must be made up of “word characters” ([A-Za-z0-9_]).
Examples:-
/student/:id // [Link]/student/12
/product/:category/:id // [Link]/product/mobile/23
/product/order/:year/and/:month // [Link]/order/2021/and/oct
/train/:from-:to // [Link]/train/ranchi-dhanbad
/location/:state.:city // [Link]/location/[Link]
[Link] = {“state” : “jh”, “city”: “ranchi”}

Route Parameter with RegX


To have more control over the exact string that can be matched by a route parameter, you can
append a regular expression in parentheses (()).
Example:-
/student/:id([0-9]{2}) // [Link]/student/12
/product/order/:year/and/:month([a-z]) // [Link]/order/2021/and/oct
[Link]

Route Parameter
[Link]() – The [Link]() function is used to add the callback triggers to route
parameters. It is commonly used to check for the existence of the data requested related to the
route parameter.
All param callbacks will be called before any handler of any route in which the param occurs,
and they will each be called only once in a request-response cycle, even if the parameter is
matched in multiple routes.
Syntax:-
[Link](name, callback)
[Link]([name1, name2,….], callback)
If name is an array, the callback trigger is registered for each parameter declared in it, in the
order in which they are declared.

Query String
/product // [Link]/product?category=mobile
[Link] = {“category” : “mobile”}
/product // [Link]/product?category=mobile&id=13
[Link] = {“category” : “mobile”, “id”:13}
Controller

Controllers can group related request handling logic separately. Instead of defining all of your
request handling logic as callback in route or route files, you may wish to organize this behavior
using Controller modules.
[Link]
[Link](‘/student/all', (req, res) =>{
[Link](‘All Student’)
})
routes/[Link]
[Link](‘/all', (req, res) =>{
[Link](‘All Student’)
})

controllers/[Link]
[Link] const allStudent = (req, res) =>{
[Link](‘/student/all', (req, res) =>{ [Link](‘All Student’)
}
[Link](‘All Student’) export { allStudent }
[Link] = { allStudent }
})
[Link](‘/student/all’, allStudent)
routes/[Link]
[Link](‘/all', (req, res) =>{
[Link](‘All Student’)
})
[Link](‘/all’, allStudent)
View

Views contain the HTML served by your application and separate your application logic from
your presentation logic. Views are stored in the views directory.
Creating View
views/[Link]
<html>
<body>
<h1>Hello Home Page</h1>
</body>
</html>

Create Route for View

Example:-
[Link](‘/’, (req, res) => {
[Link](join([Link](), 'views', '[Link]’))
});
[Link]() – process is node's global object, and .cwd() returns where node is running.
[Link]() – This is used to transfers the file at the given path. Sets the Content-Type
response HTTP header field based on the filename’s extension. Unless the root option is set in
the options object, path must be an absolute path to the file.

Static Files
CSS files, Javascript Files, image files, video files etc are considered as static files in Express
JS.
To serve static files such as images, CSS files, and JavaScript files, use the [Link]
built-in middleware function in Express.
Syntax:- [Link](root, [options])
Example:- [Link]([Link]('public’))
[Link]
To create a virtual path prefix (where the path does not actually exist in the file system) for files
that are served by the [Link] function, specify a mount path for the static directory, as
shown below:
[Link]('/static', [Link]('public’))
[Link]
The path that you provide to the [Link] function is relative to the directory from where
you launch your node process. If you run the express app from another directory, it’s safer to
use the absolute path of the directory that you want to serve:
[Link]('/static', [Link](join([Link](), 'public')))
const options = {
dotfiles: 'ignore’,
etag: false,
extensions: ['htm', 'html'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders: function (res, path, stat) {
[Link]('x-timestamp', [Link]())
}}
[Link]([Link]('public', options))
dotfiles
“allow” - No special treatment for dotfiles.
“deny” - Deny a request for a dotfile, respond with 403, then call next().
“ignore” - Act as if the dotfile does not exist, respond with 404, then call next().
NOTE: With the default value, it will not ignore files in a directory that begins with a dot.

Template Engine
A template engine enables you to use static template files in your application.
At runtime, the template engine replaces variables in a template file with actual values, and
transforms the template into an HTML file sent to the client.
This approach makes it easier to design an HTML page.
● Ejs
● Pug
● Mustache
● Nunjucks
● Dust
[Link]
•Install Template Engine
npm install ejs
[Link]
•Setup the Directory where template files are located
[Link]('views', './views’)
•Setup the Template Engine to use
[Link]('view engine', ‘ejs')

Creating Template Files


views/
[Link]
[Link]
[Link]

Creating Routes for Template Files

[Link]
[Link]('/', function (req, res) { •If the view engine property is not set, you
[Link]('index') must specify the extension of the view file.
})
routes/[Link] [Link]('view engine', ‘ejs’)
[Link]('/', function (req, res) { [Link]('/', function (req, res) {
[Link]('index’)
}) [Link]('[Link]’)
[Link](‘/about', function (req, res) {
[Link](‘about’) })
})
•When you make a request to the home
page, the [Link] file will be rendered as
HTML.
render
[Link]( ) – It renders a view and sends the rendered HTML string to the client.
Syntax:- [Link](view [, locals] [, callback])
view – The view argument is a string that is the file path of the view file to render.
This can be an absolute path, or a path relative to the views setting.
If the path does not contain a file extension, then the view engine setting determines the file
extension.
locals – It’s an object whose properties define local variables for the view.
callback – It’s a function. If provided, the method returns both the possible error and rendered
string, but does not perform an automated response. When an error occurs, the method invokes
next(err) internally.

Syntax:- [Link](view [, locals] [, callback])


Example:-
● Send the rendered view to the client
[Link](‘index’)
● Pass a local variable to the view
[Link](‘index’, { name: ‘Sonam’ })
● The rendered HTML string has to be sent explicitly
[Link]('index', function (err, html) {
[Link](html)
})

Syntax:- [Link](view [, locals] [, callback])


Example:-
[Link](‘index’, { name: ‘Sonam' }, function (err, html) {
// ...
})
EJS Template Engine

EJS (Embedded JavaScript) is a simple templating language that lets you generate HTML
markup with plain JavaScript.
● Fast compilation and rendering
● Simple template tags: <% %>
● Custom delimiters (e.g., use [? ?] instead of <% %>)
● Sub-template includes
● Ships with CLI
● Both server JS and browser support
● Static caching of intermediate JavaScript
● Static caching of templates
● Complies with the Express view system
Displaying Data - You may display data that is passed to your views by wrapping the variable in
<%= %>
Example:- <%= name %>
Comment – EJS also allows you to define comments in your views. However, unlike HTML
comments, EJS comments are not included in the HTML returned by your application.
<%# This comment will not be present in the rendered HTML %>

If

If evaluates a variable, and if that variable is “true” (i.e. exists, is not empty, and is not a false
boolean value).
Syntax:-
<% if (variable) { %>
…………..
<% } %>
Example:-
<% if name %>
</h1>Hello <%= name %></h1>
<% } %>
Conditional

if… else if… else…


•if <% if (condition) { %>
…………
<% if (condition) { %> <% } else if (condition) { %>
………… …………
<% } else { %>
<% } %> …………<% } %>

•if.. else..

<% if (condition) { %>

…………

<% } else { %>

…………

<% } %>

Loop

while
•for <% while (condition) { %>
……………………
<% for (initial; condition; incr/decr ) { %> <% } %>
……………………

<% } %> forEach


<% [Link] ((item)=> { %>
•for in ……………………
<% } )%>
<% for (const key in data ) { %> Note:- We can also do Nested Loops
……………………

<% } %>

Function Call

<% myfun() %>


Include Template

include – Include are relative to the template with the include call.
Syntax:-
<%- include(filename, object) %>
<%- include(folder/filename, object) %>
Example:-
<%- include(‘footer’,{name: ‘Sonam’}) %>
<%- include(‘myfolder/footer’, {name: ‘Sonam’}) %>

Geeky Steps

These below steps are common steps which you will follow in almost every project.
● Create Project New Folder
● Change Directory to Express Project – cd geekyshows
● Create [Link] file inside Project Folder
● Create [Link] file – npm init –y
● Install Express JS – npm i express
● Install Nodemon – npm i nodemon
● Install ejs – npm i ejs
● Install any other packages if required
● Create controllers folder – All business logic code & files will be inside this folder
● Create routes folder – All routes files will be inside this folder
● Create views folder – All presentational files will be inside this folder

Middleware

Middleware functions are functions that have access to the request object (req), the response
object (res), and the next function in the application’s request-response cycle.
The next function is a function in the Express router which, when invoked, executes the
middleware succeeding the current middleware.
Middleware functions can perform the following tasks:
● Execute any code.
● Make changes to the request and the response objects.
● End the request-response cycle.
● Call the next middleware in the stack.
Creating Middleware

middlewares/[Link]
[Link] var myLogger = function (req, res, next) {
[Link](‘Logged’)
[Link](function (req, res, next) { next()
[Link](‘Logged’) }
[Link]
next() import myLogger from
‘./middlewares/[Link]’
}) [Link](myLogger)

routes/[Link]

[Link](function (req, res, next) {

[Link](‘Logger’)

next()

})

Using Middleware

● Application Level Middleware


● Router Level Middleware

Application Level Middleware

Bind application-level middleware to an instance of the app object by using the [Link]() and
[Link]() functions, where METHOD is the HTTP method of the request that the
middleware function handles (such as GET, PUT, or POST) in lowercase.
A middleware function with no mount path. The function is executed every time the app receives
a request.
[Link](function (req, res, next) {
[Link](function (req, res, next) { [Link](‘Logged 1’)
next()
[Link](‘Logged’) }, function (req, res, next) {
next() [Link](‘Logged 2’)
}) next()
})
Application Level Middleware

middlewares/[Link]
var myLogger = function (req, res, next) {
[Link](‘Logged’)
next()
}
[Link]
import myLogger from ‘./middlewares/[Link]’
[Link](myLogger)

A Middleware function mounted on the /about path. The function is executed for any type of
HTTP request on the /about path.

[Link](‘/about', function (req, res, next) {


[Link](‘/about', function (req, res, next) { [Link](‘Logged 1’)
next()
[Link](‘Logged’) }, function (req, res, next) {
next() [Link](‘Logged 2’)
next()
}) })

middlewares/[Link]
var myLogger = function (req, res, next) {
[Link](‘Logged’)
next()
}
[Link]
import myLogger from ‘./middlewares/[Link]’
[Link](‘/about', myLogger)
Router Level Middleware

Router-level middleware works in the same way as application-level middleware, except it is


bound to an instance of [Link]().
A middleware function with no mount path. The function is executed every time the app receives
a request.

[Link](function (req, res, next) {


[Link](function (req, res, next) { [Link](‘Logged 1’)
next()
[Link](‘Logged’) }, function (req, res, next) {
next() [Link](‘Logged 2’)
}) next()
})

middlewares/[Link]
var myLogger = function (req, res, next) {
[Link](‘Logged’)
next()
}
routes/[Link]
import myLogger from ‘./middlewares/[Link]’
[Link](myLogger)

A Middleware function mounted on the /student path. The function is executed for any type of
HTTP request on the /student path.

[Link](‘/student', function (req, res, next) {


[Link](‘/student', function (req, res, next) { [Link](‘Logged 1’)
next()
[Link](‘Logged’) }, function (req, res, next) {
next() [Link](‘Logged 2’)
next()
}) })
middlewares/[Link]
var myLogger = function (req, res, next) {
[Link](‘Logged’)
next()
}
routes/[Link]
import myLogger from ‘./middlewares/[Link]’
[Link](‘/student', myLogger)

Built-in Middleware
•[Link] serves static assets such as HTML files, images, and so on.
•[Link] parses incoming requests with JSON payloads.
•[Link] parses incoming requests with URL-encoded payloads.

Third Party Middleware

Use third-party middleware to add functionality to Express apps.


npm install cookie-parser
import cookieParser from ('cookie-parser')
// load the cookie-parsing middleware
[Link](cookieParser())
[Link]
Introduction to MongoDB

MongoDB is a document database designed for ease of development and scaling. It is one of
the most powerful NoSQL system and database. Being a NoSQL means that it does not use the
usual rows and columns. This database uses a document storage format called BSON which is
a binary style of JSON documents.
Example:-
{
_id: ObjectId(“6abs665jhsj7”),
name: “Sonam”,
age: 27,
hobbies: [‘Dancing’, ‘Reading’],
city: “Ranchi”,
islogin: true
}
Locally Hosted Deployments
• MongoDB Community
• MongoDB Enterprise Advance
Cloud Hosted Deployment
•MongoDB Atlas

mongo – mongo is the command-line shell that connects to a specific instance of mongod.
When you run mongo with no parameters it defaults to connecting to the localhost on port
27017.
mongod – mongod is the primary daemon process for the MongoDB system. It handles data
requests, manages data access, and performs background management operations.
mongos – For a sharded cluster, the mongos instances provide the interface between the client
applications and the sharded cluster. The mongos instances route queries and write operations
to the shards. From the perspective of the application, a mongos instance behaves identically to
any other MongoDB instance.
mongosh – The MongoDB Shell, mongosh, is a fully functional JavaScript and [Link] 14.x
REPL environment for interacting with MongoDB deployments. You can use the MongoDB Shell
to test queries and operations directly with your database.

Show Database List – show dbs is used to show database list.


Create Database – use <db_name> is used to create database if doesn’t exist or switch if
exists.
Current Database – db is used to view Current Database.
Switch Database – use <db_name> is used to select or switch database.
Drop Database – [Link]() is used to Delete Database.
Create Collection – [Link]({“name”: “Sonam”}) If a collection does not exist,
MongoDB creates the collection when you first store data for that collection.
MongoDB provides the [Link]() method to explicitly create a collection with various
options, such as setting the maximum size or the documentation validation rules.

MongoDB provides the [Link]() method to explicitly create a collection with various
options, such as setting the maximum size or the documentation validation rules.
[Link](“student”, {
validator:{
$jsonSchema:{
bsonType: “object”,
required: [“name”, “age”],
properties:{
name:{ bsonType: “String”, description: “Must be a String and is required”},
age: { bsonType: “int”, description: “Must be a Integer and is required”},
}
}
}
})
Show Collection List – show collections is used to List Collections.
Show Validation Rules – [Link]( { name: “Collection_name" } ) is used to show
validation rule of specific collection.
Drop Collection – db.COLLECTION_NAME.drop() is used to Delete Collection.
Retrieve All Document – db.COLLECTION_NAME.find().pretty() is used to retrieve document.
Insert Single Data – db.COLLECTION_NAME.insetOne({name: “Sonam”, age: 27})
Insert Multiple Data – db.COLLECTION_NAME.insetMany([{name: “Sumit”, age: 22}, {name:
“Kunal”, age:45}])
Retrieve One Document – db.COLLECTION_NAME.findOne() is used to retrieve one document.
Limit Retrieved Document – db.COLLECTION_NAME.find().limit(NUMBER)
Retrieve Document based on field – db.COLLECTION_NAME.find({name: “Sonam”}).pretty()
Update Single Document – db.COLLECTION_NAME.updateOne(<filter>, update)
[Link]({age:27}, {$set: {name: “Jack”} })
Update Multiple Document – db.COLLECTION_NAME.updateMany(<filter>, update)
[Link]({age:27}, {$set: {name: “Jack”} })
Delete Single Document – db.COLLECTION_NAME.deleteOne(filter)
[Link]({age:27})
Delete Multiple Document – db.COLLECTION_NAME.deleteMany(filter)
[Link]({age:27})

Introduction to Mongoose
Mongoose provides a straight-forward, schema-based solution to model your application data. It
includes built-in type casting, validation, query building, business logic hooks and more, out of
the box.
Requirements
● Node
● MongoDB
How to install Mongoose
npm i mongoose

Connect MongoDB using Mongoose


connect() –Mongoose requires a connection to a MongoDB database. You can connect to a
locally hosted database with [Link]()
Syntax:- connect(uri, options, callback)
uri – It’s a String used as connection uri.
options – It’s an object passed down to the MongoDB driver's connect() function.
callback – It’s a callback function.
Example:-
[Link]("mongodb://localhost:27017/schooldb”)
[Link]("mongodb://localhost:27017/schooldb", {
useNewUrlParser: true,
useUnifiedTopology: true
});
const options = {
useNewUrlParser: true,
useUnifiedTopology: true
}
[Link]("mongodb://localhost:27017/schooldb", options);
user – It’s String
pass – It’s String
dbName – It’s String
authSource – It’s String
autoIndex – It’s Boolean

const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
user: 'geekyshows',
pass: 'merapassword',
dbName: 'schooldb',
authSource: 'schooldb'
}
[Link]("mongodb://localhost:27017", options);

Schema
A document schema is a JSON object that allows you to define the shape and content of
documents and embedded documents in a collection. You can use a schema to require a
specific set of fields, configure the content of a field, or to validate changes to a document
based on its beginning and ending states.
Defining Schema
Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection
and defines the shape of the documents within that collection.
By default, Mongoose adds an _id property to your schemas.
Syntax:-
import mongoose from 'mongoose’
const nameSchema = new [Link]({
key1: String, // String is shorthand for {type: String}
key2: Number,
key3: mongoose.Decimal128,
key4: [String],
key5: Boolean,
key6: [{ key: String, key: Date }],
key7: Date
})

Syntax:-
import mongoose from 'mongoose’
const nameSchema = new [Link]({
key1: {type:String},
key2: {type:Number},
key3: {type:mongoose.Decimal128},
key4: {type:Array},
key5: {type:Boolean},
key6: [{ key: {type:String}, key: {type:Date} }],
key7: {type:Date}
})

Example:-
import mongoose from 'mongoose’
const studentSchema = new [Link]({
name: {type:String},
age: {type:Number},
fees: {type:mongoose.Decimal128},
hobbies: {type:Array},
isactive: {type:Boolean},
comments: [{ value: {type:String}, publish: {type:Date} }],
join: {type:Date}
})

_id Property
When you create a new document with the automatically added _id property, Mongoose creates
a new _id of type ObjectId to your document.
ObjectIds encode the local time at which they were created. That means you can usually pull
the time that a document was created from its _id.
You can also overwrite Mongoose's default _id with your own _id.
Mongoose will refuse to save a document that doesn't have an _id, so you're responsible for
setting _id if you define your own _id path.

Type
•String
•Number
•Date
•Buffer
•Boolean
•Mixed
•ObjectId
•Array
•Decimal128
•Map
const clothSchema = new [Link]({
bottomwear:{
type:String
price:Number
}
})
const clothSchema = new [Link]({
bottomwear:{
type:{type:String}
price:Number
}
})

String
lowercase: boolean, whether to always call .toLowerCase() on the value
uppercase: boolean, whether to always call .toUpperCase() on the value
trim: boolean, whether to always call .trim() on the value
match: RegExp, creates a validator that checks if the value matches the given regular
expression
enum: Array, creates a validator that checks if the value is in the given array.
minLength: Number, creates a validator that checks if the value length is not less than the given
number
maxLength: Number, creates a validator that checks if the value length is not greater than the
given number
populate: Object, sets default populate options

Number
min: Number, creates a validator that checks if the value is greater than or equal to the given
minimum.
max: Number, creates a validator that checks if the value is less than or equal to the given
maximum.
enum: Array, creates a validator that checks if the value is strictly equal to one of the values in
the given array.
populate: Object, sets default populate options

Date
min: Date
max: Date
Boolean
Mongoose casts the below values to true:
true
'true'
1
'1'
'yes’
Mongoose casts the below values to false:
false
'false'
0
'0'
'no'

All Schema Types


required: boolean or function, if true adds a required validator for this property
default: Any or function, sets a default value for the path. If the value is a function, the return
value of the function is used as the default.
select: boolean, specifies default projections for queries
validate: function, adds a validator function for this property
get: function, defines a custom getter for this property using [Link]().
set: function, defines a custom setter for this property using [Link]().
alias: string, mongoose >= 4.10.0 only. Defines a virtual with the given name that gets/sets this
path.
immutable: boolean, defines path as immutable. Mongoose prevents you from changing
immutable paths unless the parent document has isNew: true.
transform: function, Mongoose calls this function when you call Document#toJSON() function,
including when you [Link]() a document.

Defining Schema

Example:-
import mongoose from 'mongoose’
const studentSchema = new [Link]({
name: {type:String, required:true},
age: { type: Number, min: 18, max: 65 },
fees: {type:mongoose.Decimal128, validate: v => v >= 5500.50},
hobbies: {type:Array},
isactive: {type:Boolean},
comments: [{ value: {type:String}, publish: {type:Date} }],
join: { type: Date, default: [Link] },
})

[Link] ( )
The [Link]() function returns the instantiated schema type for a given path.
Example:- [Link](‘age’)

Model

Models are fancy constructors compiled from Schema definitions. An instance of a model is
called a document. Models are responsible for creating and reading documents from the
underlying MongoDB database.
Compiling Schema
const studentSchema = [Link]({})
const studentModel = [Link](‘Student’, studentSchema);
The first argument is the singular name of the collection your model is for. Mongoose
automatically looks for the plural, lowercased version of your model name. Thus, for the
example above, the model Student is for the students collection in the database.

Create Document using Model


// Defining Schema
const studentSchema = [Link]({name:String})
// Compiling Schema
const studentModel = [Link](‘Student’, studentSchema);
// Creating Document
const studentDoc = new studentModel ({
name: ‘Sonam’
})
// Saving Document
await [Link]()

Create Document

// Defining Schema
const studentSchema = [Link]({name:String})
// Compiling Schema
const StudentModel = [Link](‘Student’, studentSchema);
// Creating New Document
const studentDoc = new StudentModel ({
name: ‘Sonam’
})
// Saving Document
await [Link]()

save() – It is used to save document by inserting a new document into the database if
[Link] is true, or sends an updateOne operation only with the modifications to the
database, it does not replace the whole document in the latter case.
It returns undefined if used with callback or a Promise otherwise.
Example:-

[Link]((err, result)=>{ const result = await [Link]()


if (err){ [Link](result)
[Link](err);
Mongoose validates modified paths before
} saving. If you set a field to an invalid value,
Mongoose will throw an error when you try to
else{ save() that document.

[Link](result) const result = await [Link]({


validateBeforeSave: false })
}

})
Retrieve Document

find () – The find() method returns all occurrences in the selection.


Syntax:- find(filter_object, projection_object, options_object, callback)
Example:-
await [Link]({ name: 'Sonam' }, {name:1, age:1}, {skip: 5})

Update Document

Each model has its own update method for modifying documents in the database without
returning them to your application.
findByIdAndUpdate() – It finds a matching document, updates it according to the update arg,
passing any options, and returns the found document (if any) to the callback. The query
executes if callback is passed.
Syntax:- findByIdAndUpdate(id, update, options, callback)
id can be object, number or string.
Example:- findByIdAndUpdate(“324ff2dsfsd323”, {name: “Sunil”}, {returnDocument: after})
Example:- findByIdAndUpdate(“324ff2dsfsd323”, { $set: {name: “Sunil”} } , {returnDocument:
after})
updateOne () – It is used to update single document. MongoDB will update only the first
document that matches filter regardless of the value of the multi option.
Syntax:- updateOne(filter, update, options, callback)
Example:- updateOne({_id: “324ff2dsfsd323”}, {name: “Sunil”}, {upsert: true})
upsert – If true, and no documents found, insert a new document.
updateMany () – It is used to update multiple document. MongoDB will update all documents
that match filter regardless of the value of the multi option.
Syntax:- updateMany(filter, update, options, callback)
Example:- updateMany({age: 27}, {name: “Sunil”}, {upsert: true})
Delete Document

findByIdAndDelete() – It finds a matching document then deletes it.


Syntax:- findByIdAndDelete(id, options, callback)
id can be object, number or string.
Example:- findByIdAndDelete(“324ff2dsfsd323”)
Example:- findByIdAndDelete({_id: “324ff2dsfsd323”})
deleteOne () – It is used to delete single document. MongoDB will delete only the first document
that matches conditions.
Syntax:- deleteOne(conditions, options, callback)
Example:- deleteOne({_id: “324ff2dsfsd323”})
Example:- deleteOne({_id: “324ff2dsfsd323”, age: 27})

deleteMany() – It is used to delete multiple document. MongoDB will delete all documents that
match conditions.
Syntax:- deleteMany(conditions, options, callback)
Example:- deleteMany({age: 27})
Example:- deleteMany({name: “Sonam”, age: 27})

urlencoded()

[Link]([options]) – This is a built-in middleware function in Express. It parses


incoming requests with urlencoded payloads and is based on body-parser.
This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip
and deflate encodings.
A new body object containing the parsed data is populated on the request object after the
middleware (i.e. [Link]), or an empty object ({}) if there was no body to parse, the
Content-Type was not matched, or an error occurred.
This object will contain key-value pairs, where the value can be a string or array (when
extended is false), or any type (when extended is true).
type – This is used to determine what media type the middleware will parse.
[Link]({type: “application/x-www-form-urlencoded”})
extended – This option allows to choose between parsing the URL-encoded data with the
querystring library (when false) or the qs library (when true).
[Link]({ extended: true })
redirect( )

[Link]([status,] path) – It redirects to the URL derived from the specified path, with
specified status, a positive integer that corresponds to an HTTP status code . If not specified,
status defaults to “302 “Found”.
[Link](‘/student/success')
[Link]('[Link]
[Link](301, '[Link]
[Link]('../login')

Cookie-parser
cookie-parser is a middleware which parses cookies attached to the client request object.
Parse Cookie header and populate [Link] with an object keyed by the cookie names.
npm i cookie-parser
import cookieParser from 'cookie-parser’
// var cookieParser = require('cookie-parser’)
[Link](cookieParser())

[Link]( )

[Link] () – It is used to set cookie name to value. The value parameter may be a string or
object converted to JSON.
Syntax:- [Link](name, value [, options])
Example:-
[Link]("username", "geekyshows")
[Link](“cart", 5)
[Link](“cart”, { items: [1, 2, 3] })
[Link]("username", "geekyshows", {maxAge: 5000})
[Link]("username", "geekyshows", {expires: new Date([Link]() + 900000), httpOnly:
true})
[Link]("username", "geekyshows", {path: ‘/admin’})

[Link]( )
Property Type Description

domain String Domain name for the cookie. Defaults to the domain name of
the app.

encode Function A synchronous function used for cookie value encoding.


Defaults to encodeURIComponent.

expires Date Expiry date of the cookie in GMT. If not specified or set to 0,
creates a session cookie.

httpOnly Boolean Flags the cookie to be accessible only by the web server.

maxAge Number Convenient option for setting the expiry time relative to the
current time in milliseconds.

path String Path for the cookie. Defaults to “/”.

secure Boolean Marks the cookie to be used with HTTPS only.

signed Boolean Indicates if the cookie should be signed.

sameSit Boolean or Value of the “SameSite” Set-Cookie attribute.


e String

[Link] – This property is used to get cookies.


When using cookie-parser middleware, this property is an object that contains cookies sent by
the request. If the request contains no cookies, it defaults to {}.
Example:-
[Link]
[Link]
[Link]

[Link]( )
[Link] () – It is used to Clears the cookie specified by name.
Web browsers and other compliant clients will only clear the cookie if the given options is
identical to those given to [Link](), excluding expires and maxAge.
Syntax:- [Link](name [, options])
Example:-
[Link]("username")
[Link]("username", “geekyshows”, { path: '/admin' })
[Link]("username",{ path: '/admin' })

Express-session

npm i express-session
import session from ‘express-session’
// var session = require(‘express-session’)
[Link](session({
secret: ‘iamkey',
resave: false,
saveUninitialized: true,
cookie: {path: '/', httpOnly: true, secure: false, maxAge: 5000 }
}))
secret – This is the secret used to sign the session ID cookie. This can be either a string for a
single secret, or an array of multiple secrets. If an array of secrets is provided, only the first
element will be used to sign the session ID cookie, while all the elements will be considered
when verifying the signature in requests. The secret itself should be not easily parsed by a
human and would best be a random set of characters.
resave – It forces the session to be saved back to the session store, even if the session was
never modified during the request. True If it does not implement the touch method and your
store sets an expiration date on stored sessions. False If it implements the touch method.
saveUninitialized – It forces a session that is "uninitialized" to be saved to the store. A session is
uninitialized when it is new but not modified. Choosing false is useful for implementing login
sessions, reducing server storage usage, or complying with laws that require permission before
setting a cookie. Choosing false will also help with race conditions where a client makes multiple
parallel requests without a session.
cookie – Settings object for the session ID cookie.
name – The name of the session ID cookie to set in the response. The default value is
'[Link]’.
proxy – Trust the reverse proxy when setting secure cookies.
true The "X-Forwarded-Proto" header will be used.
false All headers are ignored and the connection is considered secure only if there is a direct
TLS/SSL connection.
undefined Uses the "trust proxy" setting from express. It is default.
store – The session store instance, defaults to a new MemoryStore instance.

[Link]
To store or access session data, simply use the request property [Link], which is
(generally) serialized as JSON by the store, so nested objects are typically fine.
Example:-
[Link] = 1
[Link]
[Link]() - To regenerate the session simply invoke the method. Once complete,
a new SID and Session instance will be initialized at [Link] and the callback will be
invoked.
[Link](callback) – It destroys the session and will unset the [Link] property.
Once complete, the callback will be invoked.
[Link](callback) – It reloads the session data from the store and re-populates the
[Link] object. Once complete, the callback will be invoked.
[Link] - Each session has a unique ID associated with it. This property is an alias of
[Link] and cannot be modified. It has been added to make the session ID accessible
from the session object.
[Link] - Each session has a unique cookie object accompany it. This allows you to
alter the session cookie per visitor. For example we can set [Link] to false
to enable the cookie to remain for only the duration of the user-agent.
[Link] - Alternatively [Link] will return the time remaining in
milliseconds, which we may also re-assign a new value to adjust the .expires property
appropriately.
[Link] - The [Link] property returns the original
maxAge (time-to-live), in milliseconds, of the session cookie.
[Link] - To get the ID of the loaded session, access the request property [Link].
This is simply a read-only value set when a session is loaded/created.

[Link]

npm init -y

npm i express
npm i -D nodemon

npm i ejs

npm i mongoose

npm i express-session
npm i express-flash

npm i connect-mongo

npm i bcrypt

npm i busboy // for file upload // not working well

npm i express-fileupload // [Link]

//////////////////////////////////////////////////////

npm install express-flash --save


npm install express-session --save
npm install mongoose
npm install passport passport-local --save
npm install passport-local-mongoose --save
npm install body-parser --save

//////////////// for active class ///////////////////////////


[Link]('[Link]', {'title': 'home page', 'page_name': 'home' , data })
[Link]('[Link]', {'title': 'contact page', 'page_name': 'contact' })

<li <% if (page_name === 'home') { %>class="active" <% } %>><a


href="/business">Home</a></li>
<li <% if (page_name === 'contact') { %>class="active" <% } %>><a
href="business/contact">Contact</a></li>
////////////////////////////////////////////
=========================================

<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="[Link]
<script src="[Link]
<script
src="[Link]
<link rel="stylesheet"
href="[Link]
s">
</head>
<body>

<div class="container-fluid">

<div class="row">
<div class="col-sm-4" style="background-color:lavender;">
<form method="post">
<div class="form-group">
<label for="email">Name:</label>
<input type="text" class="form-control" id="name">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>

<div class="col-sm-8" style="background-color:lavenderblush;">


<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Action</th>

</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>
<a href="" cass="btn btn-primary btn-lg"><i class="fa fa-pencil"></i></a>
<a href="" cass="btn btn-danger btn-lg"><i class="fa fa-trash"></i></a>
</td>

</tr>

</tbody>
</table>
</div>
</div>
</div>

</body>
</html>
========================================================================
===============================

npm install nodemailer // for email sending

//[Link]
import nodemailer from 'nodemailer'
// create reusable transporter object using the default SMTP transport
const transporter = [Link]({
port: 465, // true for 465, false for other ports
host: "[Link]",
auth: {
user: 'akshayjondhale632@[Link]',
pass: 'nvpfrreijgbekrfu',
},
secure: true,
});

export default transporter

===============step 2
import transporter from "../[Link]";
static sendemail = async (req, res) => {
const {email, details} = [Link]

const mailData = {
from: 'akshayjondhale632@[Link]', // sender address
to: 'akshayjondhale632@[Link]', // list of receivers
subject: email,
text: details,
// html: '',
attachments: [
{
filename: '[Link]',
// path: 'C://Users/akshay/Desktop/expressjs/'
},
],
};

[Link](mailData, function (err, info) {


if(err)
[Link](err)
else
[Link](info);
});

[Link]("email sent")

Common questions

Powered by AI

Organizing request handling using controllers in Express enhances application architecture by promoting separation of concerns and code reusability. Controllers group related request-handling logic into separate modules, which helps decouple routing logic from business logic. This modularity improves application maintainability, as changes to application logic can be made centrally within controllers, without impacting routing code, and vice versa. It also encourages clearer organization, where controllers can be systematically developed and tested in isolation. This approach aligns with the MVC (Model-View-Controller) design pattern, supporting scalable and robust application structures .

In an Express application, middleware functions are crucial as they execute during the request-response cycle. They can perform operations such as logging, parsing request bodies, authentication, and error handling. The app.js file often includes various middleware setup that configures the application to handle different types of requests efficiently. Middleware can also be used to modify request and response objects, end the request-response cycle, or call the next middleware function in the stack. The modularity and reusability of middleware functions contribute to cleaner and more organized code structures in Express applications .

The express() function is a top-level function exported by the express module. It creates an Express application, which is essentially a JavaScript function designed to be passed to Node's HTTP servers as a callback to handle requests. The express-based application does not inherit from HTTP or HTTPS, allowing developers to easily configure the same code base to handle both HTTP and HTTPS requests. This is achieved by attaching the same Express application instance to both types of servers, providing a consistent interface for request handling regardless of the protocol .

Using view templates distinct from application logic in Express applications offers several advantages, including separation of concerns, which enhances maintainability and scalability. By isolating the presentation layer from the logic layer, developers can independently update the UI without altering the application logic or vice versa. This separation also enables front-end developers to focus on design aspects, while back-end developers can concentrate on the functionality. Furthermore, templates can be reused across different parts of an application, improving consistency and reducing redundancy .

Using the Router class in Express applications allows for modular, mountable route handlers, making the application more maintainable and scalable. Modularity helps in organizing code by separating concerns, as it enables the grouping of related routes together in different modules or files. This separation of routes aids developer collaboration, improves readability, and makes testing easier by isolating specific parts of the application. Moreover, using Router instances allows defining middleware specific to route groups, enhancing security and performance by only applying certain checks where necessary .

Regular expressions in route definitions within Express provide enhanced control over URL matching by allowing developers to define more complex path structures and validations directly in the route. For example, a route such as '/products/:id([0-9]{3})' ensures that the 'id' parameter only matches a numeric value with exactly three digits. This use of regex within routes helps to enforce specific parameter formats and can significantly reduce server errors due to invalid input formats. These patterns can match more specific and structured URLs, leading to more reliable and flexible routing in Express applications .

Schemas in Mongoose help manage data structure and validation by defining the shape and content of documents within a MongoDB collection. Through schemas, developers can specify required fields, data types, default values, and other validators like min and max for numbers, or match for strings. By enforcing these constraints, schemas ensure that data stored in the database meets certain standards, preventing inconsistent or invalid data entries. This built-in validation mechanism promotes data integrity and helps avoid runtime errors due to mismatched data types or missing fields .

Parameterized routes in Express are used to capture values from the URL and make them easily accessible within the application. Named URL segments, known as route parameters, are defined by prefixing a colon (:) to the name, such as :id or :category. When a client makes a request to a matched route, Express populates these parameters in the req.params object, which developers can then leverage in their route handling logic. This feature provides flexibility in creating dynamic routes that handle varying inputs effectively, streamlining request management and reducing the need for hardcoding specific paths into the application .

The app.param() function in Express plays a critical role in handling route parameters by providing a way to add callback triggers for route parameters. It is especially useful for parameter validation or pulling in related data before passing control to the route handler. Called before any handler of a matching route, app.param() ensures that all necessary parameter checks or preparatory operations are performed just once in a request-response cycle, thus enhancing performance and reliability. This functionality allows developers to centralize parameter handling logic, reducing redundancy and improving maintainability .

Using the app.all() method in Express allows middleware functions to be applied to all HTTP request methods (such as GET, POST, and DELETE) on specified paths. This is particularly useful for applying global logic such as authentication checks, logging, or user sessions across different types of requests to the same route. It helps in reducing duplicate code by centralizing common operations for all requests, improving code maintainability. Additionally, using app.all() can contribute to consistent request handling behaviors across an application, enhancing security and user experience by ensuring all types of requests undergo standard processing .

You might also like