NodeJS PDF
NodeJS PDF
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.
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.
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
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.
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
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.
1.Core Modules
2.Local Modules
fs fs module includes classes, methods, and events to work with file I/O.
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.
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
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
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.
For example, the following command will install ExpressJS into MyNodeProj folder.
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.
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
});
}
else if (req.url == "/student") {
}
else if (req.url == "/admin") {
}
else
res.end('Invalid Request!');
});
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
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:
r+ Open file for reading and writing. An exception occurs if the file does not exist.
w Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
}
else
res.end('Invalid Request!');
});
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
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
5.Easy to integrate with different template engines like Jade, Vash, EJS etc.
The following command will install latest version of express.js local to your project folder.
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
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.
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.
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();
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');
Continue…..
Continue…..
var connection_data = mysql_package.createConnection({
host: "localhost",
user: "root",
password: "",
database:"sample"
});
connection_data.connect(function(err) {
var sql = "INSERT INTO registration VALUES ('" + name + "','" + email + "')";