0% found this document useful (0 votes)
12 views32 pages

Module 5,6

This document discusses key topics related to Node.js including npm, callbacks, EventEmitter class, Buffers, streams, and features/advantages. It explains that npm is a package manager and registry for JavaScript packages, callbacks allow asynchronous functions, EventEmitter handles custom events, Buffers store raw data, streams process data sequentially, and Node.js is asynchronous, single-threaded, scalable, fast, cross-platform, and uses JavaScript.

Uploaded by

GolDeN Maniac
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
12 views32 pages

Module 5,6

This document discusses key topics related to Node.js including npm, callbacks, EventEmitter class, Buffers, streams, and features/advantages. It explains that npm is a package manager and registry for JavaScript packages, callbacks allow asynchronous functions, EventEmitter handles custom events, Buffers store raw data, streams process data sequentially, and Node.js is asynchronous, single-threaded, scalable, fast, cross-platform, and uses JavaScript.

Uploaded by

GolDeN Maniac
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 32

Module5

1. What is npm? How to install and uninstall different


modules using npm?.
npm is the world's largest Software Library (Registry)

npm is also a software Package Manager and Installer

The registry contains over 800,000 code packages.

Open-source developers use npm to share software.

Many organizations also use npm to manage private development.

npm is free to use

2. What is Callback in node.js ?


Callback is an asynchronous equivalent for a function. A callback function is called at

the completion of a given task. Node makes heavy use of callbacks. All the APIs of

Node are written in such a way that they support callbacks.

For example, a function to read a file may start reading file and return the control to

the execution environment immediately so that the next instruction can be executed.

Once file I/O is complete, it will call the callback function while passing the callback

function, the content of the file as a parameter. So there is no blocking or wait for File

I/O. This makes Node.js highly scalable, as it can process a high number of requests

without waiting for any function to return results.

3. Describe EventEmitter class in node.js


Node.js uses events module to create and handle custom events. The
EventEmitter class can be used to create and handle custom events
module.

The syntax to Import the events module are given below:

Syntax:

const EventEmitter = require('events');

All EventEmitters emit the event newListener when new listeners are added
and removeListener when existing listeners are removed. It also provide
one more option:

boolean captureRejections

Default Value: false

It automatically captures rejections.

Listening events: Before emits any event, it must register


functions(callbacks) to listen to the events.

Syntax:

eventEmitter.addListener(event, listener)

eventEmitter.on(event, listener)

eventEmitter.on(event, listener) and eventEmitter.addListener(event,


listener) are pretty much similar. It adds the listener at the end of the
listener’s array for the specified event. Multiple calls to the same event and
listener will add the listener multiple times and correspondingly fire
multiple times. Both functions return emitter, so calls can be chained.
Emitting events: Every event is named event in nodejs. We can trigger an
event by emit(event, [arg1], [arg2], […]) function. We can pass an arbitrary
set of arguments to the listener functions.

Syntax:

eventEmitter.emit(event, [arg1], [arg2], [...])

4. Explain Buffers in node.js

Pure JavaScript is Unicode friendly, but it is not so for binary data. While dealing with

TCP streams or the file system, it's necessary to handle octet streams. Node provides

Buffer class which provides instances to store raw data similar to an array of integers

but corresponds to a raw memory allocation outside the V8 heap.

Buffer class is a global class that can be accessed in an application without importing

the buffer module.

Creating Buffers
Node Buffer can be constructed in a variety of ways.

Method 1
Following is the syntax to create an uninitiated Buffer of 10 octets

var buf = new Buffer(10);


Method 2
Following is the syntax to create a Buffer from a given array −

var buf = new Buffer([10, 20, 30, 40, 50]);

Method 3
Following is the syntax to create a Buffer from a given string and

optionally encoding type −

var buf = new Buffer("Simply Easy Learning", "utf-8");

Though "utf8" is the default encoding, you can use any of the following encodings

"ascii", "utf8", "utf16le", "ucs2", "base64" or "hex".

5. Explain streams in node.js

Streams are one of the fundamental concepts of Node.js. Streams are a type of
data-handling methods and are used to read or write input into output
sequentially. Streams are used to handle reading/writing files or exchanging
information in an efficient way.

The official Node.js documentation defines streams as “A stream is an abstract


interface for working with streaming data in Node.js.” The stream module
provides an API for implementing the stream interface. Examples of the stream
object in Node.js can be a request to an HTTP server and process.stdout are
both stream instances. In short, Streams are objects in Node.js that lets the user
read data from a source or write data to a destination in a continuous manner.

Accessing Streams:

const stream = require('stream');

Note: What makes streams powerful while dealing with large amounts of data is
that instead of reading a file into memory all at once, streams actually read
chunks of data, processing its content data without keeping it all in memory.

Advantages of Streams over other data handling methods:

● Time Efficient: We don’t have to wait until entire file has been
transmitted. We can start processing data as soon as we have it.
● Memory Efficient: We don’t have to load huge amount of data in
memory before we start processing.

Types of Streams in Node.js: There are namely four types of streams in


Node.js.

1. Writable: We can write data to these streams. Example:


fs.createWriteStream().
2. Readable: We can read data from these streams. Example:
fs.createReadStream().
3. Duplex: Streams that are both, Writable as well as Readable.
Example: net.socket.
4. Transform: Streams that can modify or transform the data as it is
written and read. Example: zlib.createDeflate.
6. Explain features and advntages of node.js

Key Features of Node.js

Key Features of NodeJs

1. Asynchronous and Event-Driven: The Node.js library’s APIs are all


asynchronous (non-blocking) in nature. A server built with Node.JS
never waits for data from an API. from an API. After accessing an API,
the server moves on to the next one. In order to receive and track
responses of previous API requests, it uses a notification mechanism
called Events.
2. Single-Threaded: Node.js employs a single-threaded architecture with
event looping, making it very scalable. In contrast to typical servers,
which create limited threads to process requests, the event mechanism
allows the node.js server to reply in a non-blocking manner and makes
it more scalable. When compared to traditional servers like Apache
HTTP Server, Node.js uses a single-threaded program that can handle
a considerably larger number of requests.
3. Scalable: NodeJs addresses one of the most pressing concerns in
software development: scalability. Nowadays, most organizations
demand scalable software. NodeJs can also handle concurrent
requests efficiently. It has a cluster module that manages load
balancing for all CPU cores that are active. The capability of NodeJs to
partition applications horizontally is its most appealing feature. It
achieves this through the use of child processes. This allows the
organizations to provide distinct app versions to different target
audiences, allowing them to cater to client preferences for
customization.
4. Quick execution of code: Node.js makes use of the V8 JavaScript
Runtime motor, which is also used by Google Chrome. Hub provides a
wrapper for the JavaScript motor, which makes the runtime motor
faster. As a result, the preparation of requests inside Node.js becomes
faster as well.
5. Cross-platform compatibility: NodeJS may be used on a variety of
systems, including Windows, Unix, Linux, Mac OS X, and mobile
devices. It can be paired with the appropriate package to generate a
self-sufficient executable.
6. Uses JavaScript: JavaScript is used by the Node.js library, which is
another important aspect of Node.js from the engineer’s perspective.
Most of the engineers are already familiar with JavaScript. As a result, a
designer who is familiar with JavaScript will find that working with
Node.js is much easier.
7. Fast data streaming: When data is transmitted in multiple streams,
processing them takes a long time. Node.js processes data at a very
fast rate. It processes and uploads a file simultaneously, thereby saving
a lot of time. As a result, NodeJs improves the overall speed of data
and video streaming.
8. No Buffering: In a Node.js application, data is never buffered.

The Pros of Node.js


Let’s get down to the major advantages of using Node.js as server-side
programming:

1. Node.js offers an Easy Scalability


One of the key advantages of Node.js is that developers find it easy to
scale the applications in horizontal as well as the vertical directions. The
applications can be scaled in horizontal manner by the addition of
additional nodes to the existing system.
Moreover, Node.js also offers you the option of adding extra resources to
the single nodes during the vertical scaling of the application. So, it is highly
scalable and provides better option than other JavaScript servers.

2. Easy to Learn
Since JavaScript is one of the most popular programming languages, most
of the front-end developers have a good grasp over it.

It becomes much easier for them to start using the Node.js at the backend.
It is easier to learn Node.js and consumes less time to work with it.

3. Node.js is used as a Single Programming Language


Node.js offers the developers the luxury of writing the server-side
applications in the JavaScript. This allows the Node.js developers to write
both the front-end as well as the back-end web application in JavaScript
using a runtime environment.

And they don’t need to use any other server-side programming language. It
also makes the deployment of the web applications simpler because almost
all the web browsers support JavaScript.

4. The Benefit of Fullstack JS


Node.js has been regarded as a full-stack JavaScript for serving both the
client and the server-side applications.
Therefore, the advantage is that you don’t have to hire separate developers
for backend as well as the front-end development. It saves both your
valuable money and time.

Read also: Important Tips to Consider While Hiring Best Full-Stack

Developers

5. Known for Offering High Performance


It has been mentioned earlier that Node.js interprets the JavaScript code
via Google’s V8 JavaScript engine. This engine complies the JavaScript
code directly into the machine code. This makes it easier and faster to
implement the code in a effective manner.

The speed of the code execution also enhanced by runtime environment as


it supports the non-blocking I/O operations.

6. The Support of Large and Active Community


Node.js is blessed to have a large and active community of developers who
keep on continuously contributing towards its further development and
improvement.

In fact, the groups of developers are well supported by the JavaScript


programmers providing ready-made and easy solutions and codes in
GitHub. It is expected that the developers will initiate many further
developers in the future.
7. The Advantage of Caching
The open-source runtime environment of the Node.js also provides the
facility of caching single modules. Whenever there is any request for the
first module, it gets cached in the application memory.

The developers don’t have to re-execute the codes as caching allows


applications to load the web pages faster and responds more swiftly to the
user.

8. Offers the Freedom to Develop Apps


Another advantage that Node.js offers to the developers is the freedom to
develop the apps and software.

This is one essential feature, which remains absent in Ruby on Rails


imposing certain guidelines. You can begin everything from the scratch
while developing applications.

9. Getting Support for Commonly Used Tools


With Node.js, the developers can get an extended support for the various
commonly used tools. Let’s take an example. Suppose, you want to test the
source code of Node.js application; you can do so by using the Jasmin and
other such unit-testing tools.
Similarly, if you want to identify and install the project dependencies, you
can make use of npm, a powerful package manager. You can use grunt for
task running of the project.

10. Handles the Requests Simultaneously


Since the Node.js is providing the option of non-blocking I/O systems, it
relatively helps you to process several requests concurrently.

The system can handle the concurrent request handling efficiently better
than others including Ruby or Python. The incoming requests get lined up
and are executed quickly and systematically.

11. Node.js is Highly Extensible


The Node.js is known to be highly extensible, which means that you can
customize and further extend Node.js as per their requirements.

You can also make use of JSON to provide the scope for exchange of data
between the web server and the client. It also is facilitated with built-in APIs
for developing HTTP, TCP, and DNS etc. servers.

7. Explain asynchronous model of node.js

Asynchronous I/O is a form of input/output processing that permits other


processing to continue before the transmission has finished.

8. What is event loop in node js and describe working of event loop in node js
Node.js is a single-threaded event-driven platform that is capable of running non-
blocking, asynchronously programming. These functionalities of Node.js make it
memory efficient. The event loop allows Node.js to perform non-blocking I/O
operations despite the fact that JavaScript is single-threaded. It is done by
assigning operations to the operating system whenever and wherever possible.

Most operating systems are multi-threaded and hence can handle multiple
operations executing in the background. When one of these operations is
completed, the kernel tells Node.js and the respective callback assigned to that
operation is added to the event queue which will eventually be executed. This will
be explained further in detail later in this topic.

Features of Event Loop:

● Event loop is an endless loop, which waits for tasks, executes them and
then sleeps until it receives more tasks.
● The event loop executes tasks from the event queue only when the call
stack is empty i.e. there is no ongoing task.
● The event loop allows us to use callbacks and promises.
● The event loop executes the tasks starting from the oldest first.

9. Short note on REPL

REPL (READ, EVAL, PRINT, LOOP) is a computer environment similar to Shell


(Unix/Linux) and command prompt. Node comes with the REPL environment
when it is installed. System interacts with the user through outputs of
commands/expressions used. It is useful in writing and debugging the codes.
The work of REPL can be understood from its full form:

Read : It reads the inputs from users and parses it into JavaScript data structure.
It is then stored to memory.

Eval : The parsed JavaScript data structure is evaluated for the results.

Print : The result is printed after the evaluation.

Loop : Loops the input command. To come out of NODE REPL, press ctrl+c
twice

Getting Started with REPL:

To start working with REPL environment of NODE; open up the terminal (in case
of UNIX/LINUX) or the Command prompt (in case of Windows) and write node
and press ‘enter’ to start the REPL.

open node repl

The REPL has started and is demarcated by the ‘>’ symbol. Various operations
can be performed on the REPL. Below are some of the examples to get familiar
with the REPL environment.

Example: Performing Arithmetical operations in REPL


Arithmetical operations in REPL

Example: Performing operations using libraries of NODE. MATH library is being


used in below example.

Math library methods gfg

Note: using ‘math’ shows error as the library is referenced as ‘Math’ in NODE
and not ‘math’.

Example: Using variables in REPL. The keyword var is used to assign values to
variables.
Using Variables in REPL

Example: Using loops in REPL. Loops can be used in REPL as in other editors.

Note: Use ctrl – c to terminate the command and ctrl – c twice to terminate the
NODE REPL.

.help is used to list out all the commands.

Using .help in REPL


10. How to handle files in node js

The most important functionalities provided by programming languages are


Reading and Writing files from the computers. Node.js provides the functionality
to read and write files from the computer. Reading and Writing the file in Node.js
is done by using one of the coolest Node.js modules called fs module, it is one
of the most well-known built-in Node.js modules out there.

The file can be read and written in node.js in both Synchronous and
Asynchronous ways. A Synchronous method is a code blocking method which
means the given method will block the execution of code until its execution is
finished (i.e. Complete file is read or written). On the other hand, an
Asynchronous method has a callback function that is executed on completion of
execution of the given method and thus allows code to run during the completion
of its execution. Or according to modern JavaScript, asynchronous methods
return a Promise which implies the eventual completion of the ongoing
asynchronous method, the Promise will either be resolved or rejected. Thus, it is
non-blocking.

Synchronous method to read the file: To read the file in synchronous mode
we use a method in fs module which is readFileSync(). It takes two parameters
first is the file name with complete path and the second parameter is the
character encoding which is generally ‘utf-8’.

Synchronous method to writing into a file: To write the file in a


synchronous mode we use a method in fs module which is writeFileSync(). It
takes two parameters first is the file name with the complete path in which
content is to be written and the second parameter is the data to be written in
the file.

Asynchronous method to read and write from/into a file: To read/write the


file in an asynchronous mode in fs module we use readFile() and writeFile()
methods. The fs.readFile() takes three parameters first is the file name with
the complete path, the second parameter takes the character encoding which
is generally ‘utf-8’ and the third parameter is the callback function (which is
fired after reading complete file) with two parameters, one is the error in case
error occurred while reading file and second is the data that we retrieve after
reading the file and the fs.writeFile() also takes three parameters, file name
with its complete path, the second parameter is the data to be written in file
and the third is a callback function which fires in case an error occurs while
writing file.

Note: An Asynchronous method first completes the task (reading the file) and
then fires the callback function.

11. How to create web server using node js

https://www.geeksforgeeks.org/how-to-build-a-simple-web-server-with-node-js/
Module6
1. What is Express.js? What are the core features of
Express Framework?

What is Express.js
Express is a fast, assertive, essential and moderate web framework of Node.js. You can
assume express as a layer built on the top of the Node.js that helps manage a server
and routes. It provides a robust set of features to develop web and mobile applications.

Let's see some of the core features of Express framework:

● It can be used to design single-page, multi-page and hybrid web applications.


● It allows to setup middlewares to respond to HTTP Requests.
● It defines a routing table which is used to perform different actions based on
HTTP method and URL.
● It allows to dynamically render HTML Pages based on passing arguments to
templates.

Why use Express

● Ultra fast I/O


● Asynchronous and single threaded
● MVC like structure
● Robust API makes routing easy

How does Express look like


Let's see a basic Express.js app.

File: basic_express.js

1. var express = require('express');


2. var app = express();
3. app.get('/', function (req, res) {
4. res.send('Welcome to JavaTpoint!');
5. });
6. var server = app.listen(8000, function () {
7. var host = server.address().address;
8. var port = server.address().port;
9. console.log('Example app listening at http://%s:%s', host, port);
10. });

Output:

2. Explain REST API? Brief about Principles of REST


Representational State Transfer (REST) is an architectural style that defines a
set of constraints to be used for creating web services. REST API is a way of
accessing web services in a simple and flexible way without having any
processing.
REST technology is generally preferred to the more robust Simple Object Access
Protocol (SOAP) technology because REST uses less bandwidth, simple and
flexible making it more suitable for internet usage. It’s used to fetch or give some
information from a web service. All communication done via REST API uses only
HTTP request.

REST API Design Principles

Now that we’ve covered the basics and learned about the definition of REST
APIs, let’s move on to the six REST principles that guide API design:

Client-Server

This REST principle works on the concept that client and server should be
isolated from one another and permitted to develop independently. This way, you
can improve manageability across numerous platforms and increase scalability
by streamlining server components as user interface concerns are separate from
the data storage concerns.

Stateless

As per this REST principle, APIs are stateless, which means calls can be made
independent of one another. Moreover, every call includes the data essential to
complete itself effectively.

In other words, every request sent from the client to the server must include all
the info needed to comprehend the request.

Cacheable

As a stateless API can upsurge request overhead by managing huge loads of


inbound and outbound calls, a REST API design should store cacheable data.
According to this API design principle, data within a response should be indirectly
or categorized as cacheable or non-cacheable.
If a response is cacheable, the client cache is provided the right to recycle that
response data for similar requests in the future.

Uniform Interface

To decouple a client from the server, you need to have a unified interface that
permits autonomous development of the application without tightly coupling its
services, models, and actions to the API layer itself.

This design principle streamlines the whole system architecture and enhances
the visibility of communications. To attain a uniform interface, several
architectural controls are required to guide the performance of the elements
within the REST API architecture.

REST principles are defined by four interface controls, including identifying


resources, managing resources through representations, self-descriptive
communications, and hypermedia as the engine of the application state.

Layered System

REST API’s architecture includes several layers that operate together to


construct a hierarchy that helps generate a more scalable and flexible
application. Due to its layered system, an application has better security as
components in each layer can’t interact outside the subsequent layer. Moreover,
it balances loads and offers shared caches for stimulating scalability.

A layered REST API architecture system has greater stability because it restrains
component performance. so that each component can’t ‘see’ further than the
immediate layer with which it is intermingling.

Code on Demand

This REST principle allows for coding or applets to be communicated through the
API used within the application.

A REST API definition permits extending client functionality by downloading and


implementing coding in the form of applets or scripts. This streamlines clients by
decreasing the number of features essential to be pre-implemented.

Most of the time, a server returns static resource representation in XML or JSON
format. But when required, servers can deliver executable code to the client.
3. Explain Express Generator?
Node.js is an open-source and cross-platform runtime environment built on
Chrome’s V8 JavaScript engine for executing JavaScript code outside of a
browser. You need to recollect that NodeJS isn’t a framework, and it’s not a
programing language. In this article, we will discuss the Express Generator.
Express Generator is a Node.js Framework like ExpressJS which is used to
create express Applications easily and quickly. It acts as a tool for generating
express applications.
Features of Express-Generator:
● It generates express Applications in one go using only one command.
● The generated site has a modular structure that we can modify
according to our needs for our web application.
● The generated file structure is easy to understand.
● We can also configure options while creating our site like which type of
view we want to use (For example, ejs, pug, and handlebars).

4. Difference between Express.js and Node.JS

Feature Express.js Node.js

Usage It is used to build It is used to build


web-apps using server-side, input-
approaches and output, event-driven
principles of Node.js. apps.

More features than


Level of features Fewer features.
Node.js.

It is built on Google’s
Building Block It is built on Node.js.
V8 engine.

Written in JavaScript C, C++, JavaScript

Run-time platform or
environment
Framework/ Framework based on
designed for server-
Platform Node.js.
side execution of
JavaScript.

Controllers are Controllers are not


Controllers
provided. provided.

Routing Routing is provided. Routing is not


provided.

Uses middleware for


the arrangement of
Doesn’t use such a
Middleware functions
provision.
systematically server-
side.

It requires less coding It requires more


Coding time
time. coding time.

Feature Express.js Node.js

It is used to build It is used to build


web-apps using server-side, input-
Usage
approaches and output, event-driven
principles of Node.js. apps.

More features than


Level of features Fewer features.
Node.js.
It is built on Google’s
Building Block It is built on Node.js.
V8 engine.

Written in JavaScript C, C++, JavaScript

Run-time platform or
environment
Framework/ Framework based on
designed for server-
Platform Node.js.
side execution of
JavaScript.

Controllers are Controllers are not


Controllers
provided. provided.

Routing is not
Routing Routing is provided.
provided.

Uses middleware for


the arrangement of
Doesn’t use such a
Middleware functions
provision.
systematically server-
side.
It requires less coding It requires more
Coding time
time. coding time.

5. How to install Express js


Installing
Assuming you’ve already installed Node.js, create a directory to hold your application, and make that
your working directory.

$ mkdir myapp

$ cd myapp

Use the npm init command to create a package.json file for your application. For more information
on how package.json works, see Specifics of npm’s package.json handling.

$ npm init

This command prompts you for a number of things, such as the name and version of your
application. For now, you can simply hit RETURN to accept the defaults for most of them, with the
following exception:

entry point: (index.js)

Enter app.js, or whatever you want the name of the main file to be. If you want it to be index.js, hit
RETURN to accept the suggested default file name.

Now install Express in the myapp directory and save it in the dependencies list. For example:

$ npm install express


To install Express temporarily and not add it to the dependencies list:

$ npm install express --no-save

By default with version npm 5.0+ npm install adds the module to the dependencies list in the package.json
file; with earlier versions of npm, you must specify the --save option explicitly. Then, afterwards, running
npm install in the app directory will automatically install modules in the dependencies list.

6. Express.js Middleware
Express.js is a routing and Middleware framework for handling the different
routing of the webpage and it works between the request and response cycle.
Middleware gets executed after the server receives the request and before the
controller actions send the response. Middleware has the access to the request
object, responses object, and next, it can process the request before the server
send a response. An Express-based application is a series of middleware
function calls.

Middleware working

Advantages of using middleware:


● Middleware can process request objects multiple times before the
server works for that request.
● Middleware can be used to add logging and authentication functionality.
● Middleware improves client-side rendering performance.
● Middleware is used for setting some specific HTTP headers.
● Middleware helps for Optimization and better performance.

Middleware Chaining: Middleware can be chained from one to another, Hence


creating a chain of functions that are executed in order. The last function sends
the response back to the browser. So, before sending the response back to the
browser the different middleware process the request.
The next() function in the express is responsible for calling the next middleware
function if there is one.

7. Explain cookies in Express js


Cookies are simple, small files/data that are sent to client with a server request and

stored on the client side. Every time the user loads the website back, this cookie is

sent with the request. This helps us keep track of the user’s actions.

The following are the numerous uses of the HTTP Cookies −

● Session management

● Personalization(Recommendation systems)

● User tracking

To use cookies with Express, we need the cookie-parser middleware. To

install it, use the following code −

npm install --save cookie-parser


Now to use cookies with Express, we will require the cookie-parser. cookie-parser

is a middleware which parses cookies attached to the client request object. To use

it, we will require it in our index.js file; this can be used the same way as we use

other middleware. Here, we will use the following code.

var cookieParser = require('cookie-parser');

app.use(cookieParser());

cookie-parser parses Cookie header and populates req.cookies with an

object keyed by the cookie names. To set a new cookie, let us define

a new route in your Express app like −

var express = require('express');

var app = express();

app.get('/', function(req, res){

res.cookie('name', 'express').send('cookie set'); //Sets name = express

});

app.listen(3000);

To check if your cookie is set or not, just go to your browser, fire

up the console, and enter −

console.log(document.cookie);

You will get the output like (you may have more cookies set maybe due

to extensions in your browser) −

"name = express"
The browser also sends back cookies every time it queries the server. To view

cookies from your server, on the server console in a route, add the following code to

that route.

console.log('Cookies: ', req.cookies);

Next time you send a request to this route, you will receive the following output.

Cookies: { name: 'express' }

Adding Cookies with Expiration Time


You can add cookies that expire. To add a cookie that expires, just pass an object

with property 'expire' set to the time when you want it to expire. For example,

//Expires after 360000 ms from the time it is set.

res.cookie(name, 'value', {expire: 360000 + Date.now()});

Another way to set expiration time is using 'maxAge' property. Using this property,

we can provide relative time instead of absolute time. Following is an example of

this method.

//This cookie also expires after 360000 ms from the time it is set.

res.cookie(name, 'value', {maxAge: 360000});

Deleting Existing Cookies


To delete a cookie, use the clearCookie function. For example, if you need to clear a

cookie named foo, use the following code.

var express = require('express');


var app = express();

app.get('/clear_cookie_foo', function(req, res){

res.clearCookie('foo');

res.send('cookie foo cleared');

});

app.listen(3000);

You might also like