0% found this document useful (0 votes)
5 views84 pages

One

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)
5 views84 pages

One

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

Node js

Dr. Sandhya P
Professor
SCOPE
Vellore Institute of Technology - Chennai
What is Node.js?
• Node.js is an open-source, cross-platform, JavaScript Runtime
Environment.
• Open-source: source is publicly available for sharing and modification
• Cross-platform: Available on Mac, Windows and Linux
• Build end-to-end JavaScript applications.
• JavaScript runtime is an environment which provides all the necessary
components in order to use and run a JavaScript program outside the
browser.
JavaScript runtime
What can you build with Node.js?
• Traditional websites
• Backend services like APIs
• Real-time applications
• Streaming services
• CLI tools
• Multi-player games
Executing JavaScript with Node
Method 1:
• Node REPL (Read, Evaluate, Print, Loop)
Executing JavaScript with Node
• Method 2:
• Executing code in JavaScript file in command-line
Modules
• A module is an encapsulated reusable chunk of code that has its own
context
• In Node.js each file is treated as a separate module
• Module types:
• Local module – Modules that we create in our application
• Built-in module – Module that Node.js ship without of the box
• Third-party module – Module written by other developers that we can use in
our application
Example - Local Modules – add.js
Example - Local Modules – add.js
CommonJS format for Local Module
add.js
CommonJS format for Local Module
index.js
Local Module - Scope
nscope.js

batman.js

superman.js
Scope (Immediately Invoked
Function Expressions)
• Before module’s scope is executed, Node.js will wrap it with function
wrapper that provides with module scope.
• So conflict of variables or functions is avoided.
Built-in modules
• Modules shipped by Node.js
• Import them
• Built-in modules:
• path
• events
• fs
• stream
• http
path built-in module
Callback style of programming in
Node.js
• In JavaScript functions are first-class objects
• A function can be passed as an argument to a function
• A function can also be returned as values from other functions
Callback style of programming in
Node.js
Callback - asynchronous
• A callback that is often used to continue or resume code execution
after an asynchronous operation has completed.
• Callbacks are used to delay the execution of a function until a
particular time or event has occurred.
• Most of Node.js applications are asynchronous in nature
• Ex: reading data from a file, fetching data from a database
Events Module
• The events module allows us to work with events in Node.js
• An event is an action or an occurrence that has happened in our
application that we can respond to.
• Using the events module, we can dispatch our custom events and
respond to those custom events in a non-blocking manner.
• Say you go to Pizza shop and place an order (event). Then baking the
Pizza is the (response).
Events Module –Example 1
Events Module –Example 1
• EventEmitter – is the class in events module
• emit (emits an event)
• on (registers a listener)
Events Module –Example 2
Events Module – Adding more listeners
Event driven programming
Event driven programming

Observe that the event is triggering the listeners asynchronously (ie) after “Occurs before event” is
displayed.
Custom Event Driven Programming

Example
PizzaShop.js
1
Custom Event Driven Programming

Example
index1.js
1
Custom Event Driven Programming

Example 1
Streams and Buffer
• A stream is a sequence of data that is being moved from one point to
another over time.
• Stream is a built-in module that extends from EventEmitter class
• Readable stream
• Writable stream
• Duplex stream
Streams and Buffer - Example

file1.txt file2.txt(content written into file2.txt from file1.txt)


HTTP
• HTTP –request/response
• Create web server using node.js
• Node.js has access to OS functionality like networking
• Node.js has web server with event loop that runs asynchronously
HTTP – Creating a web server
example
HTTP – Creating a web server
example
HTTP – Creating a web server
example
• createServer()-function that creates a web server, and has a callback
which takes the incoming request and outgoing response as
arguments
• writeHead() – writes 200 as success code to the http response header
• end() – Adds Hello World to the end of the body of the http response
• listen() – The server listens at a specified port (3000 in our example)
and while listening (before processing request) displays the
implementation provided in its callback function.
Inspect the request/response
Inspect the request/response
HTTP-Example 2 – Writing JSON in
response
HTTP-Example 2 – Writing JSON in
response
Express
• Express is a minimalist web development framework for
NodeJS that provides a robust set of features for
creating web applications and services in NodeJS.
node.js and express
• Steps for installation
• Install node.js (npm init – y)
• Install express library (npm i express)
• Create a package called nodemon for dev dependency (npm i –save -dev
nodemon) –this is a script to restart the server.js automatically
• In package.json edit the scripts as follows:
“scripts”:{“devStart”: “nodemon server.js”}
• Create a file called server.js
• npm run devStart (will run the server code)
node.js and express
node.js and express
node.js and express (package.json –
scripts edited)
node.js and express (run in CLI)
node.js and express – Example 1
(set status code and response)
server.js
node.js and express – Example2
(download a page)

This code downloads server.js


node.js and express – Example 3
(Sending json response)
node.js and express – Example 4
(rendering a ejs file from views)
• Install ejs (ejs is the view engine) npm i ejs
• Create a views folder and add a ejs file called jam.ejs
• To use the view engine add the line app.set(‘view engine’,’ejs’)
• ‘pug’ is another view engine that could be used.
• Use render function in server.js to render the jam.ejs in browser
• Restart the server (npm i –save-dev nodemon)
node.js and express – Example 4
(rendering a ejs file from views)
server.js
jam.ejs
node.js and express – example
5(Passing data from server to views)
node.js and express – example
5(Passing data from server to views)
node.js and express (Router)
• An Express Router is an isolated instance of middleware and routes.
• Think of it as a "mini-application" capable only of performing
middleware and routing functions.
• Every Express application has a built-in app router, and you can create
additional router instances as needed.
• Routers behave like middleware themselves, making them versatile
for various use cases.
• You can use a router as an argument to app.use() or as the argument
to another router's use() method.
node.js and express – Example 6
(Router)
server.js
node.js and express – Example 6
(Router)
users.js
node.js and express – Example 6
(Router)
node.js and express – Example 7
(Chaining & middleware)
users.js (chained get, put and delete) param is the middleware that gets
request and executes the remaining code when next() is called.
node.js and express – Example 7
(Chaining & middleware)

After refreshing – observe the


console
node.js and express – Example 8
(middleware function - logger)

logger is the middleware function called in between request and response, in


this example logger is called thrice
node.js and express – Example 9
(Middleware for Handling static
pages in public folder)

app.use(express.static('public’)); is the
middleware dispensing static page index.html
in public folder.
node.js and express – Example 10
(Middleware for Handling a form)
server.js
node.js and express – Example 10
(Middleware for Handling a form)
users.js
node.js and express – Example 10
(Middleware for Handling a form)
node.js and express – Example 10
(Middleware for Handling a form)
new.ejs
node.js and express – Example 10
(Middleware for Handling a form)
node.js and express – Example 11
(Middleware for Handling a form)
node.js and express – Example 11
(Middleware for Handling a form)
node.js and express – Example 11
(Middleware for Handling a form)
node.js and express – Example 11
(Middleware for Handling a form)
node.js and express – Example 11
(Middleware for Handling a form)
• Making invalid as false, redirects to the same page
node.js and express – Example 12
(Middleware for session & cookie)
• A website is based on the HTTP protocol.
• HTTP is a stateless protocol which means at the end of
every request and response cycle, the client and the
server forget about each other.
• This is where the session comes in.
• A session will contain some unique data about that
client to allow the server to keep track of the user’s
state.
• In session-based authentication, the user’s state is
stored in the server’s memory or a database.
node.js and express – Example 12
(Middleware for session & cookie)
• When the client makes a login request to the server, the
server will create a session and store it on the server-side.
• When the server responds to the client, it sends a cookie.
• This cookie will contain the session’s unique id stored on
the server, which will now be stored on the client.
• This cookie will be sent on every request to the server.
• We use this session ID and look up the session saved in the
database or the session store to maintain a one-to-one
match between a session and a cookie.
• This will make HTTP protocol connections stateful.
node.js and express – Example 12
(Middleware for session & cookie)
• A cookie is a key-value pair that is stored in the browser.
The browser attaches cookies to every HTTP req
• On the other hand, the session data is stored on the
server-side, i.e., a database or a session store.
• Hence, it can accommodate larger amounts of data.
• To access data from the server-side, a session is
authenticated with a secret key or a session id that we
get from the cookie on every request that is sent to the
server.
node.js and express – Example 12
(Middleware for session & cookie)
• In a cookie, you can’t store a lot of data.
• A cookie cannot store any sort of user credentials or secret
information.
• If we did that, a hacker could easily get hold of that
information and steal personal data for malicious activities.
• On the other hand, the session data is stored on the server-
side, i.e., a database or a session store.
• Hence, it can accommodate larger amounts of data.
• To access data from the server-side, a session is authenticated
with a secret key or a session id that we get from the cookie
on every request.
node.js and express – Example 12
(Middleware for session & cookie)
• Steps:
• npm install express express-session cookie-parser
node.js and express – Example 12
(Middleware for session & cookie)
node.js and express – Example 12
(Middleware for session & cookie)
scdemo.js
node.js and express – Example 12
(Middleware for session & cookie)
node.js and express – Example 12
(Middleware for session & cookie)
node.js and express – Example 12
(Middleware for session & cookie)
node.js and express – Example 12
(Middleware for session & cookie)
i.html
node.js and express – Example 12
(Middleware for session & cookie)
app.css
node.js and express – Example 12
(Middleware for session & cookie)
node.js and express – Example 12
(Middleware for session & cookie)

Credentials: user1, mypassword


node.js and express – Example 12
(Middleware for session & cookie)

Redirects to login page on


logout

You might also like