0% found this document useful (0 votes)
99 views

Ch-2 Introduction To Node JS

This document provides an introduction to Node.js, including what Node.js is, its advantages, process model, event loop, and how to install Node.js. Node.js is an open-source runtime environment that allows JavaScript to be used on the server-side. It has a single-threaded, event-driven architecture and non-blocking I/O calls. The event loop listens for events and executes callbacks asynchronously, allowing Node.js to remain highly scalable and performant.

Uploaded by

Sujeet Kale
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)
99 views

Ch-2 Introduction To Node JS

This document provides an introduction to Node.js, including what Node.js is, its advantages, process model, event loop, and how to install Node.js. Node.js is an open-source runtime environment that allows JavaScript to be used on the server-side. It has a single-threaded, event-driven architecture and non-blocking I/O calls. The event loop listens for events and executes callbacks asynchronously, allowing Node.js to remain highly scalable and performant.

Uploaded by

Sujeet Kale
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/ 33

Chapter-2

Introduction to Node JS
Contents
• Introduction
• What is Node JS and its advantages
• Traditional Web Server Model
• Node JS Process model
• Installation of Node JS
• Node JS event loop
• Javascript engine converts your javascript code into machine code.
• Different browsers use different Engines.
• E.g
• Netscape was using spidermonkey
• Internet explorer –chakra
• Chrome has build its own engine called v8.
What is Node.js?

• Node.js is not a programming language.


• Node.js was written and introduced by Ryan Dahl in 2009
• Node.js is an open source ,cross-platform runtime environment for
developing server-side and networking applications
• Node.js is free
• Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
• Node.js uses JavaScript on the server
• Node.js was developed by Ryan Dahl in 2009 and its latest version is
v0.10.36
• Node.js = Runtime Environment + JavaScript Library
• Node.js = Runtime Environment + JavaScript Library
Different parts of Node.js
Features of Node.js

• Extremely fast: Node.js is built on Google Chrome's V8 JavaScript Engine, so


its library is very fast in code execution. all the operations can be done
quickly like reading or writing in the database, network connection, or file
system

•I/O is Asynchronous and Event Driven: All APIs(Application programming interface)


of Node.js library are asynchronous i.e. non-blocking. So a Node.js based server never
waits for an API to return data. The server moves to the next API after calling it and
a notification mechanism of Events of Node.js helps the server to get a response from
the previous API call. It is also a reason that it is very fast.​
• Single threaded: Node.js follows a single threaded model with
event looping.

•Highly Scalable: Node.js is highly scalable because


event mechanism helps the server to respond in a non-blocking way. ​
•No buffering: Node.js cuts down the overall processing time while uploading
audio and video files. Node.js applications never buffer any data.
These applications simply output the data in chunks. ​

•Open source: Node.js has an open source community which has produced man
y excellent modules to add additional capabilities to Node.js applications. ​
•License: Node.js is released under the MIT license. ​
"lightweight" generally refers to a system or process that requires minimal system resources and processing power.
Advantages of Node.js

1. Node.js offers an Easy Scalability


2. Easy to Learn
3. Node.js is used as a Single Programming Language
5. Known for Offering High Performance
6. The Support of Large and Active Community
7. Offers the Freedom to Develop Apps
9. Getting Support for Commonly Used Tools
10. Handles the Requests Simultaneously
11. Node.js is Highly Extensible
Traditional Web Server Model

• In the traditional web server model, each request is handled by a


dedicated thread from the thread pool.
• If no thread is available in the thread pool at any point of time then
the request waits till the next available thread.
• Dedicated thread executes a particular request and does not return to
thread pool until it completes the execution and returns a response.
Traditional Web Server Model
Node.js Process Model

• Node.js processes user requests differently when compared to a traditional


web server model.
• Node.js runs in a single process and the application code runs in a single
thread and thereby needs less resources than other platforms.
• All the user requests to your web application will be handled by a single
thread and all the I/O work or long running job is performed
asynchronously for a particular request.
• So, this single thread doesn't have to wait for the request to complete and
is free to handle the next request.
• When asynchronous I/O work completes then it processes the request
further and sends the response.
• An event loop is constantly watching for the events to be raised for an
asynchronous job and executing callback function when the job completes.
• The following figure illustrates asynchronous web server model using
Node.js.
• Node.js process model increases the performance and scalability with a few
limitations or warnings.
• Node.js is not fit for an application which performs CPU-intensive
operations like image processing or other heavy computation work because
it takes time to process a request and thereby blocks the single thread.
Node JS event loop
• 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.
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.
Example
console.log("This is the first statement");

setTimeout(function(){
console.log("This is the second statement");
}, 1000);

console.log("This is the third statement");

Output:-
This is the first statement
This is the third statement
This is the second statement
Explanation:
• In the above example, the first console log statement is pushed to the call
stack and “This is the first statement” is logged on the console and the task is
popped from the stack.
• Next, the setTimeout is pushed to the queue and the task is sent to the
Operating system and the timer is set for the task.
• This task is then popped from the stack. Next, the third console log statement
is pushed to the call stack and “This is the third statement” is logged on the
console and the task is popped from the stack.
• When the timer set by setTimeout function (in this case 1000 ms) runs out, the
callback is sent to the event queue. The event loop on finding the call stack
empty takes the task at the top of the event queue and sends it to the call
stack.
• The callback function for setTimeout function runs the instruction and
“This is the second statement” is logged on the console and the task
is popped from the stack.
• Note: In the above case, if the timeout was set to 0ms then also the
statements will be displayed in the same order. This is because
although the callback with be immediately sent to the event queue,
the event loop won’t send it to the call stack unless the call stack is
empty i.e. until the provided input script comes to an end.
Working of the Event loop:
• When Node.js starts, it initializes the event loop, processes the provided input script
which may make async API calls, schedule timers, then begins processing the event loop.
• When using Node.js, a special library module called libuv is used to perform async
operations.
• This library is also used, together with the back logic of Node, to manage a special thread
pool called the libuv thread pool.
• This thread pool is composed of four threads used to delegate operations that are too
heavy for the event loop.
• I/O operations, Opening and closing connections, setTimeouts are the example of such
operations.
• When the thread pool completes a task, a callback function is called which handles the
error(if any) or does some other operation. This callback function is sent to the event
queue. When the call stack is empty, the event goes through the event queue and sends
the callback to the call stack.
Phases of the Event loop:
Event loop in a Node.js server:

For More Reference Visit:- https://www.builder.io/blog/visual-guide-to-nodejs-event-loop


Phases of the Event loop:

• Timers: Callbacks scheduled by setTimeout() or setInterval() are executed in


this phase.
• Pending Callbacks: I/O callbacks deferred to the next loop iteration are
executed here.
• Idle, Prepare: Used internally only.
• Poll: Retrieves new I/O events.
• Check: It invokes setIntermediate() callbacks.
• Close Callbacks: It handles some close callbacks. Eg: socket.on(‘close’, …)
Install Node.js on Windows
• To install and setup an environment for Node.js, you need the following
two softwares available on your computer:
• Text Editor.
• Node.js Binary installable
• Text Editor:
• The text editor is used to type your program.
• For example: Notepad is used in Windows, vim or vi can be used on
Windows as well as Linux or UNIX.
• The source files for Node.js programs are typically named with the
extension ".js".
• The source code written in source file is simply JavaScript.
• It is interpreted and executed by the Node.js interpreter.
How to download Node.js:
• You can download the latest version of Node.js installable archive file
from https://nodejs.org/en/
Node.js First Example

• There can be console-based and web-based node.js applications.


• Node.js console-based Example:
• Node.js Console:
• Node.js comes with virtual environment called REPL (aka Node shell). REPL stands for
Read-Eval-Print-Loop.
• To launch the REPL (Node shell), open command prompt (in Windows) and
type node as shown below.
• You can execute an external JavaScript file by writing node fileName
command.
• For example, assume that Hello.js containing console.log("Hello
World");
• Now, you can execute node-exampel.js from command prompt as
shown below.
Node.js web-based Example

• A node.js web application contains the following three parts:


• Import required modules: The "require" directive is used to load a
Node.js module.
• Create server: You have to establish a server which will listen to client's
request similar to Apache HTTP Server.
• Read request and return response: Server created in the second step will
read HTTP request made by client which can be a browser or console and
return the response.
1. Import required module: The first step is to use ?require? directive to load http module
and store returned HTTP instance into http variable. For example:
var http = require("http");
2. Create server: In the second step, you have to use created http instance and call
http.createServer() method to create server instance and then bind it at port 8081 using
listen method associated with server instance. Pass it a function with request and response
parameters and write the sample implementation to return "Hello World". For example:
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
var http = require("http");
http.createServer(function (request, response) {
response.write("Hello World");
response.end();
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
Combine step1 and step2 together in a file named "main.js".
File: main.js
var http = require("http");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
How to start your server:

Now command prompt is open:


• Go to start menu and click on the
Node.js command prompt.
After that execute the main.js to start Now server is started.
the server as follows: Make a request to Node.js server:
Open http://127.0.0.1:8081/ in any browser. You will see the
following result.

Now, if you make any changes in the "main.js" file, you need to again run the "node main.js"
command.

You might also like