DOC_LM_Unit5 (2)
DOC_LM_Unit5 (2)
js :
5.1 Concepts, working and Features
5.1.1 Downloading Node.js
5.2 Setting up Node.js server(HTTP server)
5.2.1 Installing on window
5.2.2 Components
5.2.2.1 Required modules, Create Server(http.createServer())
5.2.2.2 Request and response
5.3 Built-in Modules
5.3.1 require() function
5.3.2 User defined module: create and include
5.3.3 HTTP module
5.4 Node.js as Web-server:
5.4.1 createServer() , writeHead() method
5.4.2 Reading Query String, Split Query String
5.5 File System Module:
5.5.1 Read Files (readFile())
5.5.2 Create Files(appendFile(),open(),writeFile())
5.5.3 Update Files(appendFile(),writeFile())
5.5.4 Delete Files(unlink())
5.5.5 Rename Files(rename())
Applications of Node.js
▪ The following are some of the areas where Node.js is proving to be an effective
technology partner-
o Single Page Applications
o Data-Intensive Real-time Applications
o I/O bound Applications
o JSON APIs based Applications
o Data Streaming Applications
Advantages:
1. High performance for real-time applications.
2. Easy scalability
3. Cost effective
Disadvantages:
1. Reduces performance when handling Heavy Computing Tasks
2. Node.js invites a lot of code changes due to Unstable API
3. Node.js Asynchronous Programming Model makes it difficult to maintain code
4. Choose Wisely – Lack of Library Support can Endanger your Code
5. High demand with a few Experienced Node.js Developers
Node.js 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.
Now let’s understand each part of the Node.js architecture and the workflow of a web server
developed using Node.js.
Parts of 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
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.
• Clients send requests to the webserver to interact with the web application. Requests
can be non-blocking or blocking e.g Querying the data , updating the data or deleting
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.
Advantages of Node.js Architecture:
Node.js Architecture comes with several advantages that give the server-side platform a
distinct upper-hand when compared to other server-side languages:
• Handling multiple concurrent client requests is fast and easy: With the use of Event
Queue and Thread Pool, the Node.js server enables efficient handling of a large
number of incoming requests.
• No need for creating multiple threads: Event Loop handles all requests one-by-one,
so there is no need to create multiple threads. Instead, a single thread is sufficient to
handle a blocking incoming request.
All of these advantages contribute to making the servers developed using Node.js much faster
and responsive when compared to those developed using other server development
technologies.
EXMAPLE 2:
Components
Node.js includes several components for developing, testing, and deploying enterprise
applications. The primary components are
• Node CLI(command line interface)
• NPM
• package.json
• third-party modules such as Mongoose and MongoDB
• and Node Core modules such as http, url, querystring, and fs.
Modules in Node.js
Modules in Node.js are like JavaScript libraries — a set of related functions that you can
include in your application. Every Node.js file can be considered a module that can export
code for reuse in other parts of the application.
Module properties/method
1. exports: The object that a module can export for use in other modules.
2. require(): A function that is used to import modules into other modules.
3. module: The object that represents the current module.
Types of Node
1) Core Modules:
Node.js has many built-in modules that are part of the platform and come
with Node.js installation. These modules can be loaded into the program by using
the required function.
Syntax:
const module = require('module_name');
2) Local Modules: Unlike built-in and external modules, local modules are created locally in
our Node.js application. These modules are included in our program in the same way as
we include the built in module.
Ex : //FileName : sum.js
exports.add=function(n,m){
return n+m;
};
Exports keyword is used to make properties and methods available outside the file.
In order to include the add function in our index.js file we use the require function.
Ex : let sum = require('./sum')
3) Third-party modules
Create Server(http.createServer()):
Creating an HTTP server using http.createServer() in Node.js is a fundamental way to serve
requests and responses. The http module in Node.js provides this functionality
There are 3 steps
I. Import the http module: The http module is built into Node.js, so you don't need to
install it.
II. Create a server: Use http.createServer() to create a new server instance. The
function takes a callback that is executed each time the server receives a request.
III. Listen on a port: Use the server.listen() method to specify the port and hostname
the server will use.
// Send a response
res.end('Hello, World! Welcome to my Node.js server.\n');
Node.js as Web-server:
Node.js allows developers to use JavaScript to write back-end code, even though traditionally
it was used in the browser to write front-end code. Having both the frontend and backend
together like this reduces the effort it takes to make a web server, which is a major reason why
Node.js is a popular choice for writing back-end code.
Example
Module Type How to Import Installation
Module
Built-in Module http, fs const fs = require('fs'); No
Yes (npm install
Third-party Module Lodash const _ = require('lodash');
lodash)
const math =
Custom Module math.js No
require('./math');
Ex:
const fs = require('fs');
// Write a file
fs.writeFileSync('example.txt', 'Hello, Node.js!');
console.log('File created.');
3. Execution:
▪ In this part, the code of the module or code inside the wrapper function is run or
executed by the NodeJS runtime.
4. Returning Exports:
▪ In this part, require function returns the exports of required module. These exports
are stored in module.exports.
▪ Use module.exports to export single variable/class/function. If you want to export
multiple function or variables use exports ( exports.add = (a,b)=>a+b ).
5. Caching:
▪ At the end all modules are cached after the first time they are loaded.
▪ E.g. If we require the same module multiple times, we will get the same result. So
the code and modules are executed in the first call and in a subsequent call, results
are retrieved from the cache.
createServer()
The http.createServer() method turns your computer into an HTTP server. The
http.createServer() method creates an HTTP Server object. The HTTP Server object can listen
requestListener : Optional. Specifies a function to be executed every time the server gets
a request. This function is called a requestListener, and handles request from the user, as well
as response back to the user.
The function passed in the http.createServer() will be executed when the client goes to the
url http://localhost:8081.
▪ Steps to run the code:
o Save the above code in a file with .js extension
o Open the command prompt and go to the folder where the file is there
using cd command.
o Run the command node file_name.js
o Open the browser and go the url http://localhost:8081
▪ The http.createServer() method includes request object that can be used to get
information about the current HTTP request e.g. url, request header, and data.
▪
index.js
const http = require('http');
Reading File
Use the fs.readFile() method to read the physical file asynchronously.
Syntax : fs.readFile(fileName [,options], callback)
Ex : 1
var fs = require('fs');
fs.readFile('Demo.txt', 'uft-8' ,function (err, file) {
if (err) throw err;
console.log('Saved!');
});
<html>
<body>
<h1>My Header</h1>
<p>My <b>Fantastic</b> paragraph.</p>
</body>
</html>
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('DataHtml.html', function(err, data) {
res.writeHead(200, {'Content-Type':'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
▪ fs.appendFile()
▪ fs.open()
▪ fs.writeFile()
1) fs.appendFile()
The fs.appendFile() method appends specified content to a file. If the file does not exist,
the file will be created:
var fs = require('fs');
2) fs.open()
The fs.open() method takes a "flag" as the second argument, if the flag is "w" for
"writing", the specified file is opened for writing. If the file does not exist, an empty file
is created:
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.
3) fs.writeFile()
The fs.writeFile() method replaces the specified file and content if it exists. If the file
does not exist, a new file, containing the specified content, will be created:
var fs = require('fs');
Update files
The File System module has methods for updating files:
• fs.appendFile()
• fs.writeFile()
1) The fs.appendFile() method appends the specified content at the end of the specified file:
var fs = require('fs');
var fs = require('fs');
Delete files
To delete a file with the File System module, use the fs.unlink() method. The fs.unlink()
method deletes the specified file:
var fs = require('fs');
Rename files
To rename a file with the File System module, use the fs.rename() method. The fs.rename()
method renames the specified file:
var fs = require('fs');