You are on page 1of 66

What is Node.js?

Node.js is an open-source server-side runtime environment built on Chrome's V8 JavaScript


engine. It provides an event driven, non-blocking (asynchronous) I/O and cross-platform
runtime environment for building highly scalable server-side application using JavaScript.

Node.js can be used to build different types of applications such as command line
application, web application, real-time chat application, REST API server etc. However, it is
mainly used to build network programs like web servers, similar to PHP, Java, or ASP.NET.

Node.js was written and introduced by Ryan Dahl in 2009.


1. Easy to learn:
Most developers have a good grasp of JavaScript for it being one of the most popular
programming languages.
Developers who are already good in JavaScript find it easy to use Node.js at the backend. It
is quite easy to learn Nodejs and it also consumes lesser time.

2. Supported widely by Google Chrome:


The search engine is empowered by Node.js and it not only aids in the front-end
development but also has a great impact on the backend. Nodejs is supported by the
Google V8 engine, which has the power to execute at the same time in the front end using
JavaScript.
Google lists Node.js as one of the fastest runtime system engines so that’s amazing. Also,
with Nodejs it is easy to find mistakes in the front end as well as the back end.
3. Node.js offers easy scalability:
One of the key benefits offered by Nodejs is that it makes it easy for developers to scale
the application in horizontal as well as vertical directions. The application can be scaled
in a horizontal dimension by adding extra nodes to the current system.
Furthermore, Node.js also allows adding extra resources to a single node during the
vertical scaling of the application. Hence, NodeJS is highly scalable and offers greater
options than other JavaScript servers.

4. Full-stack JavaScript:
Node.js has regarded as a full-stack JavaScript for serving server-side applications as
well as the client.
The benefit of using Nodejs is that you need not hire remote developers for the front-end
and back-end, which saves you valuable money and time.
5. Offer High Performance:
As mentioned earlier, Node.js interprets the JavaScript code through Google’s V8 JavaScript
engine. The engine compiles JavaScript code directly into the machine code. Hence, it becomes
easy to implement the code. Moreover, it can be done quickly and in an effective manner.

6. Single Programming Language:


With Node.js it becomes possible for developers to write the server-side application in
JavaScript. This means that when you Hire Nodejs developers they can write both front-end
and back-end applications in JavaScript using a runtime environment.

7. Large and Active Community:


Node.js have a large and active community of developers who keep on contributing to the
further improvement and development of this server-side JavaScript.
Developers working on Node.js have been supported well by JavaScript programmers who
provide them with easy and ready-made solutions and codes in GitHub.
8. The ability of Caching:
The open-source runtime environment of Node.js provides the ability to cache a single module.
The entire request for the first modules gets cached in the application memory.

9. Support for Commonly Used Tools:


With Node.js, developers receive extended support for various commonly used tools. If you want
to test the source code of the Node.js application, you can do it by using Jasmin and other such
testing tools. Similarly, if you want to install or identify the project dependencies, you can make
use of npm, which is a powerful package manager.

10. Handles Requests Simultaneously:


Node.js provides the option of non-blocking I/O systems. It helps you to process several server
requests simultaneously.
Node.js system can handle concurrent requests better than Ruby or Python. The incoming
requests get lined up and are addressed quickly and systematically.
1. API is not stable:
One of the key problems that developers encounter while working on Node.js is
the Application Programming Interface keeps on changing at frequent intervals and does
not remain stable.
At times, you will see a new API with multiple backward-incompatible changes. As a
result, developers are obliged to make changes in the accessible code bases to remain in
tune with the latest version of Node.js API.

2. Library Support System is not strong:


Compared to other languages, JavaScript does not have a robust and well-equipped library
system.
As a result, users are forced to take support from the commonly available library for executing
tasks, such as processing and handling database operations, Object-Relational Mapping, XML
parsing, etc. This makes it difficult for developers to implement common programming tasks
using Node.js.
3. Asynchronous Programming Model:
If you want to boost the scalability of the application, the requirement is that the
application should adopt an asynchronous programming model.
However, developers find this model to be more difficult as compared to linear blocking
I/O programming.
Another disadvantage of the asynchronous programming model is that the code
becomes clumsy, and programmers need to depend on the nested calls.

4. Not Suited for CPU-intensive Tasks:


Node.js applications are single-threaded, which means that they can only use one CPU
core at a time. This can be a bottleneck for applications that are CPU-intensive.
5. Doesn’t have a Strong Library Support System
JavaScript does not come with a well-equipped library system compared to other
programming languages. This results in developers being forced to take support of a
common library for various tasks like processing the images, Object-Relational Mapping
(ORM), handling database operations and more.
Traditional Web Server Model
Traditional Web Server Model

The traditional web server model consists of a pool of threads which may process
requests. Each time a new request comes in, it is assigned to a different thread in the
pool. In the event a request is received and a thread is not available, the request will
have to wait until a previous request finishes, a response is returned, and the thread is
returned to the thread pool. In this way, the web server model is synchronous, or
blocking.
NodeJs Process Model
The NodeJS process model can be explained with three architectural features of NodeJS.
1.Single-threaded event loop
2.Non-Blocking I/O Model
3.Event-driven and Asynchronous by default

Single-threaded event loop:


NodeJS runs on a single-threaded environment which means each user request processes on a
single thread only. This makes it use lesser resources and run smoothly using events and emitters.

NodeJS has two types of threads: one Event loop also referred to as the main thread, and the k
Workers also referred to as the background thread. When a new user request comes in, it is placed in
an event queue. Every request consists of a synchronous and asynchronous part. The synchronous
part of the request is handled on the main thread while the asynchronous part is handled in the
background via the k Workers/ background threads.
Non-Blocking I/O Model :
Blocking codes or operations are the ones that need to be completed entirely before moving on to
another operation. Non-blocking codes are asynchronous and accept callback functions to operate.
As mentioned, every request has a synchronous and asynchronous part. The main thread of NodeJS
does not keep waiting for the background thread to complete the asynchronous I/O operations. The
main thread keeps switching between other requests to process their synchronous part while the
background thread process the asynchronous part.

Event-Driven and Asynchronous By Default:


Once the execution of the background thread is complete, the background thread emits events to
notify the main thread. Callback functions are associated with asynchronous processes. If the main
thread is not free, the request waits for the main thread to be free and then takes up the callback
request for further execution.
How to Install NodeJS
Installing NodeJS is straightforward. If you already have Node installed in your machine, you can
skip this section. If not, then follow along.

Here are the steps to download NodeJS on your machine:


• Navigate to https://nodejs.org/
• Download the LTS Version of NodeJS for your operating system
• Run the installer and follow the installation wizard. Simply answer Yes to all the questions.
• Once the installation is complete, open a new terminal or command prompt window and run
the following command to verify that NodeJS is installed correctly: node -v. If you see the
version of NodeJS printed in your terminal, Congratulations! You have now successfully
installed NodeJS on your machine.
Node.js Console/REPL
Node.js comes with virtual environment called REPL (aka Node shell).
REPL stands for Read-Eval-Print-Loop. It is a quick and easy way to test simple Node.js/JavaScript
code.
To launch the REPL (Node shell), open command prompt (in Windows) or terminal (in Mac or
UNIX/Linux) and type node as shown below. It will change the prompt to > in Windows and MAC.
You can execute an external JavaScript file by executing the node fileName command. For example,
the following runs mynodejs-app.js on the command prompt/terminal and displays the result.

Now, you can execute mynodejs-app from command prompt as shown below.
To exit from the REPL terminal, press Ctrl + C twice or write .exit and press Enter.
The following table lists important REPL commands.
Node.js Module
Module in Node.js is a simple or complex functionality organized in single or multiple JavaScript

files which can be reused throughout the Node.js application.

Each module in Node.js has its own context, so it cannot interfere with other modules or

pollute global scope. Also, each module can be placed in a separate .js file under a separate

folder.

Node.js Module Types

Node.js includes three types of modules:

1.Core Modules

2.Local Modules

3.Third Party Modules


Node.js Core Modules
Node.js is a light weight framework. The core modules include bare minimum functionalities of
Node.js. These core modules are compiled into its binary distribution and load automatically
when Node.js process starts. However, you need to import the core module first in order to use it
in your application.

Core Module Description


http module includes classes, methods and events to create Node.js http
http
server.
url url module includes methods for URL resolution and parsing.

querystring querystring module includes methods to deal with query string.

path path module includes methods to deal with file paths.

fs fs module includes classes, methods, and events to work with file I/O.

util util module includes utility functions useful for programmers.


Loading Core Modules
In order to use Node.js core or NPM modules, you first need to import it using require() function
as shown below.

var module = require('module_name');

As per above syntax, specify the module name in the require() function. The require() function
will return an object, function, property or any other JavaScript type, depending on what the
specified module returns.

The following example demonstrates how to use Node.js http module to create a web server.

var http = require('http');


In the example, require() function returns
var server = http.createServer(function(req, res){ an object because http module returns its
//write code here functionality as an object, you can then
use its properties and methods using dot
}); notation e.g. http.createServer().
server.listen(5000);
Node.js Local Module
Local modules are modules created locally in your Node.js application. These modules include
different functionalities of your application in separate files and folders. You can also package it
and distribute it via NPM, so that Node.js community can use it.

Writing Simple Module

Let’s take the example for simple logging module which logs the information, warning or error

to the console.

In Node.js, module should be placed in a separate JavaScript file. So, create a Log.js file and

write the following code in it.


Log.js

var log = {
info: function (info) {
console.log('Info: ' + info);
},
warning:function (warning) {
console.log('Warning: ' + warning);
},
error:function (error) {
console.log('Error: ' + error);
}
};

module.exports = log

In the above example of logging module, we have created an object with three functions - info(),
warning() and error(). At the end, we have assigned this object to module.exports. The
module.exports in the above example exposes a log object as a module.

The module.exports is a special object which is included in every JS file in the Node.js application by
default. Use module.exports or exports to expose a function, object or variable as a module in
Node.js.
Loading Local Module
To use local modules in your application, you need to load it using require() function in the same
way as core module. However, you need to specify the path of JavaScript file of the module.

Log.js app.js

var log = { var myLogModule = require('./Log.js');


info: function (info) {
console.log('Info: ' + info); myLogModule.info('Node.js started');
},
warning:function (warning) {
console.log('Warning: ' + warning);
}, In the above example, app.js is using log module.
error:function (error) { First, it loads the logging module using require()
console.log('Error: ' + error); function and specified path where logging module
} is stored. Logging module is contained in Log.js
}; file in the root folder. So, we have specified the
path './Log.js' in the require() function. The '.'
module.exports = log denotes a root folder.
Export Module in Node.js
The module.exports is a special object which is included in every JavaScript file in the Node.js
application by default. The module is a variable that represents the current module, and exports is an
object that will be exposed as a module. So, whatever you assign to module.exports will be exposed
as a module.

As mentioned above, exports


is an object. So it exposes
whatever you assigned to it
as a module. For example, if
you assign a string literal
then it will expose that string
literal as a module.
NPM - Node Package Manager
Node Package Manager (NPM) is a command line tool that installs, updates or uninstalls Node.js
packages in your application. It is also an online repository for open-source Node.js packages. The
node community around the world creates useful modules and publishes them as packages in this
repository.

NPM is included with Node.js installation. NPM performs the operation in two modes: global and
local. In the global mode, NPM performs operations which affect all the Node.js applications on the
computer whereas in the local mode, NPM performs operations for the particular local directory
which affects an application in that directory only.
Install Package Locally
Use the following command to install any third party module in your local Node.js project folder.

C:\>npm install <package name>

For example, the following command will install ExpressJS into MyNodeProj folder.

C:\MyNodeProj> npm install express

All the modules installed using NPM are installed under node_modules folder. The above
command will create ExpressJS folder under node_modules folder in the root folder of your project
and install Express.js there.
Add Dependency into package.json
Use --save at the end of the install command to add dependency entry into package.json of your
application.
For example, the following command will install ExpressJS in your application and also adds
dependency entry into the package.json.

C:\MyNodeProj> npm install express --save


Node.js Web Server

To access web pages of any web application, you need a web server. The web server will handle
all the http requests for the web application e.g IIS is a web server for ASP.NET web applications
and Apache is a web server for PHP or Java web applications.
Node.js provides capabilities to create your own web server which will handle HTTP requests
asynchronously.

server.js
var http = require('http'); // 1 - Import Node.js core module

var server = http.createServer(function (req, res) { // 2 - creating server

//handle incomming requests here..

});

server.listen(5000); //3 - listen for any incoming requests

console.log('Node.js web server at port 5000 is running..')


In the above example, we import the http module using require() function. The http module is a
core module of Node.js, so no need to install it using NPM. The next step is to call createServer()
method of http and specify callback function with request and response parameter. Finally, call
listen() method of server object which was returned from createServer() method with port
number, to start listening to incoming requests on port 5000. You can specify any unused port
here.

C:\> node server.js


Node.js web server at port 5000 is running..
Handle HTTP Request
The http.createServer() method includes request and response parameters which is supplied by
Node.js. The request object can be used to get information about the current HTTP request e.g.,
url, request header, and data. The response object can be used to send a response for a current
HTTP request.

var http = require('http'); // Import Node.js core module

var server = http.createServer(function (req, res) { //create web server

if (req.url == '/') { //check the URL of the current request

// set response header


res.writeHead(200, { 'Content-Type': 'text/html' });

// set response content


res.write('<html><body><p>This is home Page.</p></body></html>');
res.end();

}
else if (req.url == "/student") {

res.writeHead(200, { 'Content-Type': 'text/html' });


res.write('<html><body><p>This is student Page.</p></body></html>');
res.end();

}
else if (req.url == "/admin") {

res.writeHead(200, { 'Content-Type': 'text/html' });


res.write('<html><body><p>This is admin Page.</p></body></html>');
res.end();

}
else
res.end('Invalid Request!');

});

server.listen(5000); // listen for any incoming requests

console.log('Node.js web server at port 5000 is running..')


In the above example, req.url is used to check the url of the current request and based on that
it sends the response. To send a response, first it sets the response header using writeHead()
method and then writes a string as a response body using write() method. Finally, Node.js web
server sends the response using end() method.

Now, run the above web server as shown below.

C:\> node server.js


Node.js web server at port 5000 is running..
For Windows users, point your browser to http://localhost:5000 and see the following result.

http://localhost:5000/student
Node.js File System
Node.js includes fs module to access physical file system. The fs module is responsible for all the

asynchronous or synchronous file I/O operations.

Reading a File
Use the fs.readFile() method to read the physical file asynchronously.
Signature:
fs.readFile(fileName [,options], callback)

Parameter Description:
• filename: Full path and name of the file as a string.
• options: The options parameter can be an object or string which can include encoding and flag.
The default encoding is utf8 and default flag is "r".
• callback: A function with two parameters err and fd. This will get called when readFile operation
completes.
The following example demonstrates reading existing TestFile.txt asynchronously.

// console.log(data.toString('utf8'));

The above example reads TestFile.txt (on Windows) asynchronously and executes callback
function when read operation completes. This read operation either throws an error or completes
successfully. The err parameter contains error information if any. The data parameter contains the
content of the specified file.
The following example demonstrates reading existing TestFile.txt synchronously.

// console.log(data.toString('utf8'));
Writing a File
Use the fs.writeFile() method to write data to a file. If file already exists then it overwrites the
existing content otherwise it creates a new file and writes data into it.

Signature:
fs.writeFile(filename, data[, options], callback)

Parameter Description:
filename: Full path and name of the file as a string.
Data: The content to be written in a file.
options: The options parameter can be an object or string which can include encoding, mode and flag.
The default encoding is utf8 and default flag is "r".
callback: A function with two parameters err and fd. This will get called when write operation
completes.
The following example creates a new file called test.txt and writes "Hello World" into it
asynchronously.
In the same way, use the fs.appendFile() method to append the content to an existing file.
Open File
Alternatively, you can open a file for reading or writing using the fs.open() method.

Signature:
fs.open(path, flags[, mode], callback)
Parameter Description:

path: Full path with name of the file as a string.


Flag: The flag to perform operation
Mode: The mode for read, write or readwrite. Defaults to 0666 readwrite.
callback: A function with two parameters err and fd. This will get called when file open operation
completes.
The following table lists all the flags which can be used in read/write operation.
Flag Description
r Open file for reading. An exception occurs if the file does not exist.

r+ Open file for reading and writing. An exception occurs if the file does not exist.

rs Open file for reading in synchronous mode.


rs+ Open file for reading and writing, telling the OS to open it synchronously. See notes for 'rs' about
using this with caution.

w Open file for writing. The file is created (if it does not exist) or truncated (if it exists).

wx Like 'w' but fails if path exists.


w+ Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).

wx+ Like 'w+' but fails if path exists.


a Open file for appending. The file is created if it does not exist.

ax Like 'a' but fails if path exists.


a+ Open file for reading and appending. The file is created if it does not exist.

ax+ Like 'a+' but fails if path exists.


// Load html web pages using node.js

var http = require('http'); // Import Node.js core modules


let fs = require('fs');

var server = http.createServer(function (req, res) { //create web server

if (req.url == '/') { //check the URL of the current request

// set response header


res.writeHead(200, { 'Content-Type': 'text/html' });

// set response content


fs.readFile('./homepage.html', null, function (error, data) {
if (error) {
res.writeHead(404);
res.write('Whoops! File not found!');
} else {
res.write(data);
}
res.end();
});
}
else if (req.url == "/student") {
res.writeHead(200, { 'Content-Type': 'text/html' });
// set response content
fs.readFile('./student.html', null, function (error, data) {
if (error) {
res.writeHead(404);
res.write('Whoops! File not found!');
} else {
res.write(data);
}
res.end();
});
}
else if (req.url == "/admin") {
res.writeHead(200, { 'Content-Type': 'text/html' });
// set response content
fs.readFile('./admin.html', null, function (error, data) {
if (error) {
res.writeHead(404);
res.write('Whoops! File not found!');
} else {
res.write(data);
}
res.end();
});

}
else
res.end('Invalid Request!');

});

server.listen(5000); // listen for any incoming


requests

console.log('Node.js web server at port 5000 is


running..')
Express.js
"Express is a fast, unopinionated minimalist web framework for Node.js“.

Express.js is a web application framework for Node.js. It provides various features


that make web application development fast and easy which otherwise takes more
time using only Node.js.

Express.js is based on the Node.js middleware module called connect which in turn
uses http module. So, any middleware which is based on connect will also work with
Express.js.
Advantages of Express.js

1.Makes Node.js web application development fast and easy.

2.Easy to configure and customize.

3.Allows you to define routes of your application based on HTTP methods and URLs.

4.Includes various middleware modules which you can use to perform additional tasks

on request and response.

5.Easy to integrate with different template engines like Jade, Vash, EJS etc.

6.Allows you to define an error handling middleware.

7.Easy to serve static files and resources of your application.

8.Allows you to create REST API server.

9.Easy to connect with databases such as MongoDB, Redis, MySQL


Install Express.js
You can install express.js using npm. The following command will install latest version of
express.js globally on your machine so that every Node.js application on your machine
can use it.

npm install -g express

The following command will install latest version of express.js local to your project folder.

C:\MyNodeJSApp> npm install express –save

As you know, --save will update the package.json file by specifying express.js
dependency.
Express.js Web Application

Express.js provides an easy way to create web server and render HTML pages for
different HTTP requests by configuring routes for your application.

Web Server
First of all, import the Express.js module and create the web server as shown below.

Express.js

var express = require('express');


var app = express();

// define routes here..

var server = app.listen(5000, function () {


console.log('Node server is running..');
});
In the above example, we imported Express.js module using require() function. The
express module returns a function. This function returns an object which can be used
to configure Express application

The app object includes methods for routing HTTP requests, configuring middleware,
rendering HTML views and registering a template engine.

The app.listen() function creates the Node.js web server at the specified host and
port. It is identical to Node's http.Server.listen() method.
Configure Routes
Use app object to define different routes of your application. The app object includes get(), post(),
put() and delete() methods to define routes for HTTP GET, POST, PUT and DELETE requests
respectively.

var express = require('express’);


var app = express(); app.put('/update-data', function (req, res) {
res.send('PUT Request’);
app.get('/', function (req, res) { });
res.send('<html><body><h1>HelloWorld
</h1></body></html>'); }); app.delete('/delete-data', function (req, res) {
res.send('DELETE Request'); });
app.post('/submit-data', function (req, res) {
res.send('POST Request’); var server = app.listen(5000, function () {
}); console.log('Node server is running..’);
});
The first parameter is a path of a route which will start after base URL. The callback function
includes request and response object which will be executed on each request.

Handle POST Request


Here, you will learn how to handle HTTP POST request and get data from the submitted form.

First, create Index.html file in the root folder of your application and write the following HTML
code in it.
Body Parser
To handle HTTP POST request in Express.js version 4 and above, you need to install
middleware module called body-parser.

This body-parser module parses the JSON, buffer, string and url encoded data
submitted using HTTP POST request.

Install body-parser using NPM as shown below.

npm install body-parser --save


import body-parser and get the POST request data as shown below.
app.js
var express = require('express’);
var app = express();
var bodyParser = require("body-parser"); In this example, POST data can
be accessed using req.body. The
app.use(bodyParser.urlencoded({ extended: false })); req.body is an object that includes
app.get('/', function (req, res) { properties for each submitted
res.sendFile('index.html', { root: __dirname }); form. Index.html contains
}); firstName and lastName input
types, so you can access it using
app.post('/submit-student-data', function (req, res) { req.body.firstName and
var name = req.body.firstName + ' ' + req.body.lastName; req.body.lastName.
res.send(name + ' Submitted Successfully!’);
});
var server = app.listen(5000, function () {
console.log('Node server is running..'); });
Without using database

Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="/submit-student-data" method="post">
Name: <input name="username" type="text" /> <br />
email: <input name="useremail" type="text" /> <br />
<input type="submit" />
</body>
</html>
Without using database

Server.js
var express = require('express');
var app = express();

var bodyParser = require("body-parser");


app.use(bodyParser.urlencoded({ extended: false }));

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


res.sendFile('index.html', { root: __dirname });
});

app.post('/submit-student-data', function (req, res) {


var name = req.body.name + ' ' + req.body.email;

res.send(name + ' Submitted Successfully!');


});

var server = app.listen(3000, function () {


console.log('Node server is running..');
});
With using database

Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="/submit-student-data" method="post">
Name: <input name="username" type="text" /> <br />
email: <input name="useremail" type="text" /> <br />
<input type="submit" />
</body>
</html>
Server.js
var express = require('express');
var app = express();
var mysql_package = require('mysql');

var bodyParser = require("body-parser");


app.use(bodyParser.urlencoded({ extended: false }));

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


res.sendFile('index.html', { root: __dirname });
});

var server = app.listen(3000, function () {


console.log('Node server is running..');
});

// Create the connection using the server,username and password.


//In my scenario - server is the localhost,
//username is root, password is empty, database is sample

Continue…..
Continue…..
var connection_data = mysql_package.createConnection({
host: "localhost",
user: "root",
password: "",
database:"sample"
});
connection_data.connect(function(err) {

app.post('/submit-student-data', function (req, res) {

var name = req.body.username;


var email = req.body.useremail;

var sql = "INSERT INTO registration VALUES ('" + name + "','" + email + "')";

connection_data.query(sql, function (err, result) {


console.log("Row inserted Successfully!");
res.send("Row inserted Successfully!");
});
});
});

You might also like