0% found this document useful (0 votes)
8 views5 pages

Intoduction To Node JS

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
8 views5 pages

Intoduction To Node JS

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

INTRODUCTION TO NODE JS

Server-side Scripting using node


 Node.js is an open-source, cross-platform runtime environment that allows developers to
create server-side tools and applications using JavaScript
 Node.js can be used to generate dynamic page content, create, open, read, write, delete,
and close files on the server, collect form data, and add, delete, modify data in your
database.
 Node.js applications are written in JavaScript, and can be run within the Node.js runtime on
OS X, Microsoft Windows, and Linux.
 Node.js also provides a rich library of various JavaScript modules which simplifies the
development of web applications using Node.js to a great extent.
 Node.js = Runtime Environment + JavaScript Library

A common task for a web server can be to open a file on the server and return the content to the
client.
Here is how Node.js handles a file request:
1. Sends the task to the computer's file system.
2. Ready to handle the next request.
3. When the file system has opened and read the file, the server returns the content to the
client.
Node.js eliminates the waiting, and simply continues with the next request.
Node.js runs single-threaded, non-blocking, asynchronous programming, which is very memory
efficient
What is a Node.js File?
 Node.js files contain tasks that will be executed on certain events
 A typical event is someone trying to access a port on the server
 Node.js files must be initiated on the server before having any effect
 Node.js files have extension ".js"
Before creating an actual "Hello, World!" application using Node.js, let us see the components of a
Node.js application. A Node.js application consists of the following three important components −
 Import required modules − We use the require directive to load Node.js modules.
 Create server − A server which will listen to client's requests similar to Apache HTTP
Server.
 Read request and return response − The server created in an earlier step will read
the HTTP request made by the client which can be a browser or a console and return
the response.

Creating Node.js Application


Step 1 - Import Required Module
We use the require directive to load the http module and store the returned HTTP instance into an
http variable as follows −
var http = require("http");

Step 2 - Create Server


We use the created http instance and call http.createServer() method to create a server instance
and then we bind it at port 8081 using the listen method associated with the server instance. Pass it
a function with parameters request and response. Write the sample implementation to always
return "Hello World".
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/');
The above code is enough to create an HTTP server which listens, i.e., waits for a request over 8081
port on the local machine.
Step 3 - Testing Request & Response
Let's put step 1 and 2 together in a file called main.js and start our HTTP server as shown below −
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/ /');
Now execute the main.js to start the server as follows −
$ node main.js
Verify the Output. Server has started.
Server running at http://127.0.0.1:8081/
Open http://127.0.0.1:8081/ in any browser and observe the following result.
Congratulations, you have your first HTTP server up and running which is responding to all the HTTP
requests at port 8081.

Create a Node.js file named "myfirst.js", and add the following code:
myfirst.js
var http = require('http');

http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8081);
Save the file on your computer: C:\Users\Your Name\myfirst.js
The code tells the computer to write "Hello World!" if anyone (e.g. a web browser) tries to access
your computer on port 8081.

How to run a node application:


Node.js files must be initiated in the "Command Line Interface" program of your computer.
How to open the command line interface on your computer depends on the operating system. For
Windows users, press the start button and look for "Command Prompt", or simply write "cmd" in
the search field.
Navigate to the folder that contains the file "myfirst.js", the command line interface window should
look something like this:
C:\Users\Your Name>_

Initiate the Node.js File


To initialize a new Node.js project, you can use the npm init command.
This command will prompt you with a series of questions to create a package.json file for
your project.
The package.json file contains metadata about your project, such as its name, version, and
dependencies.
Here are the steps to initialize a new Node.js project:
1. Open your terminal and navigate to the directory where you want to create your project.
2. Type npm init and press enter.
3. Answer the questions that appear in the terminal. You can press enter to accept the default
values or type in your own values.
4. Once you have answered all the questions, a package.json file will be created in your project
directory.
That’s it! You have successfully initialized a new Node.js project.
Go to the command line interface, write node myfirst.js and hit enter:
Initiate "myfirst.js":
C:\Users\Your Name>node myfirst.js
Now, your computer works as a server!
If anyone tries to access your computer on port 8081, they will get a "Hello World!" message in
return!
Start your internet browser, and type in the address: http://localhost:8081

Node.js Server Architecture


Node.js uses the “Single Threaded Event Loop” architecture to handle multiple concurrent clients.
Node.js Processing Model is based on the JavaScript event-based model along with the JavaScript
callback mechanism.
Fig: Node.js architecture
Now let’s understand each part of the Node.js architecture and the workflow of a web server
developed using Node.js.
Parts of the Node.js Architecture:
 Requests
Incoming requests can be blocking (complex) or non-blocking (simple), depending upon
the tasks that a user wants to perform in a web application
 Node.js Server
Node.js server is a server-side platform that takes requests from users, processes those
requests, and returns responses to the corresponding users
 Event Queue
Event Queue in a Node.js server stores incoming client requests and passes those
requests one-by-one into the Event Loop
 Thread Pool
Thread pool consists of all the threads available for carrying out some tasks that might be
required to fulfill client requests
 Event Loop
Event Loop indefinitely receives requests and processes them, and then returns the
responses to corresponding clients
 External Resources
External resources are required to deal with blocking client requests, external resources
are used. They can be of any type (computation, storage, etc).

The Workflow of Node.js Architecture:


A web server developed using Node.js typically has a workflow that is quite similar to the diagram
illustrated below. Let’s explore this flow of operations in detail.
Fig: Node.js Architecture Workflow
 Clients send requests to the webserver to interact with the web application. Requests can
be non-blocking or blocking:
-Querying for data
-Deleting data
-Updating the data
 Node.js retrieves the incoming requests and adds those requests to the Event Queue
 The requests are then passed one-by-one through the Event Loop. It checks if the
requests are simple enough to not require any external resources
 Event Loop processes simple requests (non-blocking operations), such as I/O Polling, and
returns the responses to the corresponding clients
A single thread from the Thread Pool is assigned to a single complex request. This thread is
responsible for completing a particular blocking request by accessing the external resources, such as
compute, database, file system, etc.
Once, the task is carried out completely, the response is sent to the Event Loop that in turn sends
that response back to the Client.

You might also like