Module 5,6
Module 5,6
the completion of a given task. Node makes heavy use of callbacks. All the APIs of
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
Syntax:
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
Syntax:
eventEmitter.addListener(event, listener)
eventEmitter.on(event, listener)
Syntax:
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
Buffer class is a global class that can be accessed in an application without importing
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
Method 3
Following is the syntax to create a Buffer from a given string and
Though "utf8" is the default encoding, you can use any of the following encodings
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.
Accessing Streams:
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.
● 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.
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.
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.
Developers
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.
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.
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.
● 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.
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.
Loop : Loops the input command. To come out of NODE REPL, press ctrl+c
twice
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.
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.
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.
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’.
Note: An Asynchronous method first completes the task (reading the file) and
then fires the callback function.
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.
File: basic_express.js
Output:
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
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.
Layered System
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.
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).
It is built on Google’s
Building Block It is built on Node.js.
V8 engine.
Run-time platform or
environment
Framework/ Framework based on
designed for server-
Platform Node.js.
side execution of
JavaScript.
Run-time platform or
environment
Framework/ Framework based on
designed for server-
Platform Node.js.
side execution of
JavaScript.
Routing is not
Routing Routing is provided.
provided.
$ 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:
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:
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
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.
● Session management
● Personalization(Recommendation systems)
● User tracking
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
app.use(cookieParser());
object keyed by the cookie names. To set a new cookie, let us define
});
app.listen(3000);
console.log(document.cookie);
You will get the output like (you may have more cookies set maybe due
"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.
Next time you send a request to this route, you will receive the following output.
with property 'expire' set to the time when you want it to expire. For example,
Another way to set expiration time is using 'maxAge' property. Using this property,
this method.
//This cookie also expires after 360000 ms from the time it is set.
res.clearCookie('foo');
});
app.listen(3000);