0% found this document useful (0 votes)
53 views108 pages

NodeJS Hiren Sir

Node.js is an open-source server-side runtime environment built on Chrome's V8 JavaScript engine, designed for building scalable applications using JavaScript. It features asynchronous, non-blocking I/O, making it efficient for handling multiple requests simultaneously, and is suitable for I/O bound applications, but not for CPU-intensive tasks. The document also covers the setup of a Node.js development environment, the use of Node Package Manager (NPM), and the structure of Node.js modules.

Uploaded by

Archi Jariwala
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)
53 views108 pages

NodeJS Hiren Sir

Node.js is an open-source server-side runtime environment built on Chrome's V8 JavaScript engine, designed for building scalable applications using JavaScript. It features asynchronous, non-blocking I/O, making it efficient for handling multiple requests simultaneously, and is suitable for I/O bound applications, but not for CPU-intensive tasks. The document also covers the setup of a Node.js development environment, the use of Node Package Manager (NPM), and the structure of Node.js modules.

Uploaded by

Archi Jariwala
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/ 108

NodeJS

Mr. Hiren Raval


Assistant Professor
IT Department
SVIT Vasad
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.
• Node.js official web site: https://nodejs.org
• Node.js on github: https://github.com/nodejs/node
• Node.js community conference http://nodeconf.com
Features of Node.js
• Following are some of the important features that make Node.js the first choice of
software architects.
• Asynchronous and Event Driven − All APIs of Node.js library are
asynchronous, that is, non-blocking. It essentially means 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.
• Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js
library is very fast in code execution.
• Single Threaded but Highly Scalable − Node.js uses a single threaded model
with event looping. Event mechanism helps the server to respond in a non-
blocking way and makes the server highly scalable as opposed to traditional
servers which create limited threads to handle requests. Node.js uses a single
threaded program and the same program can provide service to a much larger
number of requests than traditional servers like Apache HTTP Server.
• No Buffering − Node.js applications never buffer any data. These applications
simply output the data in chunks.
Why Node.js?
• 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 PHP or ASP handles a file request:
– Sends the task to the computer's file system.
– Waits while the file system opens and reads the file.
– Returns the content to the client.
– Ready to handle the next request.

• Here is how Node.js handles a file request:


– Sends the task to the computer's file system.
– Ready to handle the next request.
– 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, asynchronously programming,
which is very memory efficient.
What Can Node.js Do?
• Node.js can generate dynamic page content
• Node.js can create, open, read, write, delete,
and close files on the server
• Node.js can collect form data
• Node.js can add, delete, modify data in your
database
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"
Advantages of Node.js
• Node.js is an open-source framework under MIT license.
(MIT license is a free software license originating at the
Massachusetts Institute of Technology (MIT).)
• Uses JavaScript to build entire server side application.
• Lightweight framework that includes bare minimum
modules. Other modules can be included as per the need of
an application.
• Asynchronous by default. So it performs faster than other
frameworks.
• Cross-platform framework that runs on Windows, MAC or
Linux
Where to Use Node.js?
• Following are the areas where Node.js is
proving itself as a perfect technology partner.
– I/O bound Applications
– Data Streaming Applications
– Data Intensive Real-time Applications (DIRT)
– JSON APIs based Applications
– Single Page Applications
Where Not to Use Node.js?
• It is not advisable to use Node.js for CPU
intensive applications.
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.
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. Internally, Node.js uses libev for the event loop which in turn
uses internal C++ thread pool to provide asynchronous I/O.
Node.js Process Model
• The following figure illustrates asynchronous web server model using Node.js.

• Node.js process model increases the performance and scalability with a few
caveats. 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.
Concepts
• The following diagram depicts some important parts of
Node.js
Setup Node.js Development Environment

• Node.js development environment can be setup in Windows,


Mac, Linux and Solaris. The following tools/SDK are required
for developing a Node.js application on any platform.
• Node.js
• Node Package Manager (NPM)
• IDE (Integrated Development Environment) or TextEditor
• NPM (Node Package Manager) is included in Node.js
installation since Node version 0.6.0., so there is no need to
install it separately.
Setup Node.js Development Environment
• Install Node.js on Windows
• Visit Node.js official web site https://nodejs.org. It will automatically
detect OS and display download link as per your Operating System. For
example, it will display following download link for 64 bit Windows
OS.
Setup Node.js Development Environment
• Download node MSI for windows by clicking on 8.11.3 LTS or 10.5.0
Current button. We have used the latest version 10.5.0 for windows
through out these tutorials.
• After you download the MSI, double-click on it to start the installation
as shown below.
• Click Next to read and accept
the License Agreement and
then click Install.
• It will install Node.js quickly
on your computer.
• Finally, click finish to complete

the installation.
Setup Node.js Development Environment

• Verify Installation
• Once you install Node.js on your computer, you can verify it
by opening the command prompt and typing node -v. If
Node.js is installed successfully then it will display the version
of the Node.js installed on your machine, as shown below.
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 now test pretty much any Node.js/JavaScript expression in REPL. For
example, if your write "10 + 20" then it will display result 30 immediately in
new line.
• The + operator also concatenates strings as in browser's JavaScript.
• You can also define variables and perform some operation on them.
• If you need to write multi line JavaScript expression or function then just
press Enter whenever you want to write something in the next line as a
continuation of your code. The REPL terminal will display three dots (...), it
means you can continue on next line. Write .break to get out of continuity mode.
• For example, you can define a function and execute it as shown below.

• can execute an external JavaScript file by writing node filename command. For
example, assume that node-example.js is on C drive of your PC with following
code.
console.log("Hello World");
REPL Commands
• Read − Reads user's input, parses the input into JavaScript data-structure,
and stores in memory.
• Eval − Takes and evaluates the data structure.
• Print − Prints the result.
• Loop − Loops the above command until the user presses ctrl-c twice.
• ctrl + c − terminate the current command.
• ctrl + c twice − terminate the Node REPL.
• ctrl + d − terminate the Node REPL.
• Up/Down Keys − see command history and modify previous commands.
• tab Keys − list of current commands.
• .help − list of all commands.
• .break − exit from multiline expression.
• .clear − exit from multiline expression.
• .save filename − save the current Node REPL session to a file.
• .load filename − load file content in current Node REPL session.
Node Package Manager (NPM)
• Node Package Manager (NPM) provides two main functionalities −
• Online repositories for node.js packages/modules which are
searchable on search.nodejs.org
• Command line utility to install Node.js packages, do version
management and dependency management of Node.js packages.
• NPM comes bundled with Node.js installable after v0.6.3 version.
To verify the same, open console and type the following command
and see the result −
Global vs Local Installation
• By default, NPM installs any dependency in the local mode.
Here local mode refers to the package installation in
node_modules directory lying in the folder where Node
application is present. Locally deployed packages are
accessible via require() method. For example, when we
installed express module, it created node_modules directory in
the current directory where it installed the express module.
• Globally installed packages/dependencies are stored in system
directory. Such dependencies can be used in CLI (Command
Line Interface) function of any node.js but cannot be imported
using require() in Node application directly. Now let's try
installing the express module using global installation.
Node.js Basics
• Node.js supports JavaScript. So, JavaScript syntax on Node.js is
similar to the browser's JavaScript syntax.
• Primitive Types
• Node.js includes following primitive types:
– String
– Number
– Boolean
– Undefined
– Null
– RegExp
• Everything else is an object in Node.js.
• Loose Typing
• JavaScript in Node.js supports loose typing like the browser's
Node.js Basics
• Object Literal
• Object literal syntax is same as browser's JavaScript.
• var obj = {
authorName: 'Ryan Dahl',
language: 'Node.js'
}
• Functions
• Functions are first class citizens in Node's JavaScript, similar to the browser's
JavaScript. A function can have attributes and properties also. It can be treated
like a class in JavaScript.

• function Display(x)
{
console.log(x);
}
Node.js Basics
• Buffer
• Node.js includes an additional data type called Buffer (not available in browser's
JavaScript). Buffer is mainly used to store binary data, while reading from a file or
receiving packets over the network.
• process object
• Each Node.js script runs in a process. It includes process object to get all the
information about the current process of Node.js application.
• The following example shows how to get process information in REPL
using process object.
• Defaults to local
• Node's JavaScript is different from browser's JavaScript when it comes to global scope.
In the browser's JavaScript, variables declared without var keyword become global. In
Node.js, everything becomes local by default.
• Access Global Scope
• In a browser, global scope is the window object. In Node.js, global object represents
the global scope.
• To add something in global scope, you need to export it using export or module.export.
The same way, import modules/object using require() function to access it from the
Node.js Basics
• Access Global Scope
• In a browser, global scope is the window object. In
Node.js, global object represents the global scope.
• To add something in global scope, you need to export it using export or
module.export. The same way, import modules/object using require()
function to access it from the global scope.
• exports.log = {
console: function(msg)
{ console.log(msg);
},
file: function(msg) { // log to file here }
}

• Now, you can import log object using require() function and use it
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 implements CommonJS modules standard.
CommonJS is a group of volunteers who define JavaScript
standards for web server, desktop, and console
application.
Node.js Module Types
• Node.js includes three types of modules:
– Core Modules
– Local Modules
– 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.
• The following table lists some of the important core modules in Node.js.
Core Module Description
http http module includes classes, methods and events to create Node.js
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.
Loading Core Modules
• The following example demonstrates how to use
Node.js http module to create a web server.
var http = require('http');
var server = http.createServer(function(req, res)
{ //write code here });
server.listen(5000);
• In the above example, require() function returns an
object because http module returns its functionality as
an object, you can then use its properties and methods
using dot notation e.g. http.createServer().
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. For example, if you need to
connect to MongoDB and fetch data then you can
create a module for it, which can be reused in
your application.
Writing Simple Module
• Let's write 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.
• 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
• 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.
• 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
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.
• The following example demonstrates how to use the above logging module
contained in Log.js.
• var myLogModule = require('./Log.js'); myLogModule.info('Node.js
started');
• In the above example, app.js is using log module. First, it loads the logging
module using require() 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 '.' denotes a
root folder.
• The require() function returns a log object because logging module exposes
an object in Log.js using module.exports. So now you can use logging
module as an object and call any of its function using dot notation e.g
myLogModule.info() or myLogModule.warning() or myLogModule.error()
What is Callback?
• Callback is an asynchronous equivalent for a function. A callback
function is called at the completion of a given task. Node makes
heavy use of callbacks. All the APIs of Node are written in such a
way that they support callbacks.
• For example, a function to read a file may start reading file and
return the control to the execution environment immediately so
that the next instruction can be executed. Once file I/O is
complete, it will call the callback function while passing the
callback function, the content of the file as a parameter. So there
is no blocking or wait for File I/O. This makes Node.js highly
scalable, as it can process a high number of requests without
waiting for any function to return results.
• Blocking Code Example
• Non-Blocking Code Example
What is Callback?
• These two examples explain the concept of blocking and non-
blocking calls.
• The first example shows that the program blocks until it reads the
file and then only it proceeds to end the program.
• The second example shows that the program does not wait for file
reading and proceeds to print "Program Ended" and at the same
time, the program without blocking continues reading the file.
• Thus, a blocking program executes very much in sequence. From
the programming point of view, it is easier to implement the logic
but non-blocking programs do not execute in sequence. In case a
program needs to use any data to be processed, it should be kept
within the same block to make it sequential execution.
What is Callback?
• These two examples explain the concept of blocking and non-
blocking calls.
• The first example shows that the program blocks until it reads the
file and then only it proceeds to end the program.
• The second example shows that the program does not wait for file
reading and proceeds to print "Program Ended" and at the same
time, the program without blocking continues reading the file.
• Thus, a blocking program executes very much in sequence. From
the programming point of view, it is easier to implement the logic
but non-blocking programs do not execute in sequence. In case a
program needs to use any data to be processed, it should be kept
within the same block to make it sequential execution.
Node.js - Event Loop
• Node.js is a single-threaded application, but it can
support concurrency via the concept
of event and callbacks. Every API of Node.js is
asynchronous and being single-threaded, they
use async function calls to maintain concurrency.
Node uses observer pattern. Node thread keeps an
event loop and whenever a task gets completed, it
fires the corresponding event which signals the
event-listener function to execute.
Event-Driven Programming
• Node.js uses events heavily and it is also one of the reasons
why Node.js is pretty fast compared to other similar
technologies. As soon as Node starts its server, it simply
initiates its variables, declares functions and then simply waits
for the event to occur.
• In an event-driven application, there is generally a main loop
that listens for events, and then triggers a callback function
when one of those events is detected.
Event-Driven Programming
• Although events look quite similar to callbacks, the difference
lies in the fact that callback functions are called when an
asynchronous function returns its result, whereas event
handling works on the observer pattern. The functions that
listen to events act as Observers. Whenever an event gets
fired, its listener function starts executing. Node.js has
multiple in-built events available through events module and
EventEmitter class which are used to bind events and event-
listeners as follows −

// Import events module


var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();
Event-Driven Programming
• Following is the syntax to bind an event handler with an event

// Bind event and event handler as follows


eventEmitter.on('eventName', eventHandler);

• We can fire an event programmatically as follows −


// Fire an event
eventEmitter.emit('eventName');

• Example
Node.js - Event Emitter
• Many objects in a Node emit events, for
example, a net.Server emits an event each time a
peer connects to it, an fs.readStream emits an
event when the file is opened. All objects which
emit events are the instances of
events.EventEmitter.
• Node.js allows us to create and handle custom
events easily by using events module. Event
module includes EventEmitter class which can
be used to raise and handle custom events.
EventEmitter Class
• As we have seen in the previous section, EventEmitter class lies
in the events module. It is accessible via the following code −

// Import events module


var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();

• When an EventEmitter instance faces any error, it emits an


'error' event. When a new listener is added, 'newListener' event
is fired and when a listener is removed, 'removeListener' event
is fired.
• EventEmitter provides multiple properties
like on and emit. on property is used to bind a function with the
event and emit is used to fire an event.
What is the use of listener?
• An event listener is a procedure or function in a
computer program that waits for an event to
occur
• event-driven architecture in which certain
kinds of objects (called "emitters") emit named
events that cause Function objects ("listeners")
to be called
Sr.No. Method & Description

1 addListener(event, listener)
Adds a listener at the end of the listeners array for the specified event. No
checks are made to see if the listener has already been added. Multiple calls
passing the same combination of event and listener will result in the listener
being added multiple times. Returns emitter, so calls can be chained.

2 on(event, listener)
Adds a listener at the end of the listeners array for the specified event. No
checks are made to see if the listener has already been added. Multiple calls
passing the same combination of event and listener will result in the listener
being added multiple times. Returns emitter, so calls can be chained.

3 once(event, listener)
Adds a one time listener to the event. This listener is invoked only the next time
the event is fired, after which it is removed. Returns emitter, so calls can be
chained.

4 removeListener(event, listener)
Removes a listener from the listener array for the specified event. Caution − It
changes the array indices in the listener array behind the listener.
removeListener will remove, at most, one instance of a listener from the listener
array. If any single listener has been added multiple times to the listener array
for the specified event, then removeListener must be called multiple times to
remove each instance. Returns emitter, so calls can be chained.
Sr.No. Method & Description

5 removeAllListeners([event])
Removes all listeners, or those of the specified event. It's not a good idea to
remove listeners that were added elsewhere in the code, especially when it's
on an emitter that you didn't create (e.g. sockets or file streams). Returns
emitter, so calls can be chained.

6 setMaxListeners(n)
By default, EventEmitters will print a warning if more than 10 listeners are
added for a particular event. This is a useful default which helps finding
memory leaks. Obviously not all Emitters should be limited to 10. This
function allows that to be increased. Set to zero for unlimited.

7 listeners(event)
Returns an array of listeners for the specified event.

8 emit(event, [arg1], [arg2], [...])


Execute each of the listeners in order with the supplied arguments. Returns
true if the event had listeners, false otherwise.
Class Methods
Sr.No. Method & Description
1 listenerCount(emitter, event)
Returns the number of listeners for a given event.
Events
Sr.No. Events & Description

1 newListener
•event − String: the event name
•listener − Function: the event handler function
This event is emitted any time a listener is added. When this event is
triggered, the listener may not yet have been added to the array of
listeners for the event.

2 removeListener
•event − String The event name
•listener − Function The event handler function
This event is emitted any time someone removes a listener. When this
event is triggered, the listener may not yet have been removed from
the array of listeners for the event.
Buffers
• Pure JavaScript is Unicode friendly, but it is not so
for binary data. While dealing with TCP streams or
the file system, it's necessary to handle octet
streams. Node provides Buffer class which provides
instances to store raw data similar to an array of
integers but corresponds to a raw memory
allocation outside the V8 heap.
• Buffer class is a global class that can be accessed in
an application without importing the buffer
module.
Creating Buffers
• Node Buffer can be constructed in a variety of ways.
• Method 1
– Following is the syntax to create an uninitiated Buffer of 10 octets −
var buf = new Buffer(10);
• Method 2
– Following is the syntax to create a Buffer from a given array
var buf = new Buffer([10, 20, 30, 40, 50]);
• Method 3
– Following is the syntax to create a Buffer from a given string and
optionally encoding type −
var buf = new Buffer("Simply Easy Learning", "utf-8");
Writing to Buffers
• Syntax
• Following is the syntax of the method to write into a Node Buffer

– buf.write(string[, offset][, length][, encoding])
• Parameters
• Here is the description of the parameters used −
– string − This is the string data to be written to buffer.
– offset − This is the index of the buffer to start writing at. Default value
is 0.
– length − This is the number of bytes to write. Defaults to buffer.length.
– encoding − Encoding to use. 'utf8' is the default encoding.
• Return Value
• This method returns the number of octets written. If there is not
enough space in the buffer to fit the entire string, it will write a
Reading from Buffers
• Syntax
• Following is the syntax of the method to read data from
a Node Buffer −
– buf.toString([encoding][, start][, end])
• Parameters
• Here is the description of the parameters used −
– encoding − Encoding to use. 'utf8' is the default encoding.
– start − Beginning index to start reading, defaults to 0.
– end − End index to end reading, defaults is complete buffer.
• Return Value
• This method decodes and returns a string from buffer
data encoded using the specified character set
Convert Buffers to JSON
• Syntax
• Following is the syntax of the method to
convert a Node Buffer into JSON object
−buf.toJSON()
• Return Value
• This method returns a JSON-representation of
the Buffer instance.
Concatenate Buffers
• Syntax
• Following is the syntax of the method to
concatenate Node buffers to a single Node Buffer
– Buffer.concat(list[, totalLength])
• Parameters
• Here is the description of the parameters used −
– list − Array List of Buffer objects to be concatenated.
– totalLength − This is the total length of the buffers
when concatenated.
• Return Value
• This method returns a Buffer instance.
Compare Buffers
• Syntax
• Following is the syntax of the method to compare
two Node buffers
– buf.compare(otherBuffer);
• Parameters
• Here is the description of the parameters used
– otherBuffer − This is the other buffer which will be
compared with buf.
• Return Value
• Returns a number indicating whether it comes
before or after or is the same as the otherBuffer in
Copy Buffer
• Syntax
• Following is the syntax of the method to copy a node buffer
– buf.copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd])
• Parameters
• Here is the description of the parameters used
– targetBuffer − Buffer object where buffer will be copied.
– targetStart − Number, Optional, Default: 0
– sourceStart − Number, Optional, Default: 0
– sourceEnd − Number, Optional, Default: buffer.length
• Return Value
• No return value. Copies data from a region of this buffer to a
region in the target buffer even if the target memory region
overlaps with the source. If undefined, the targetStart and
sourceStart parameters default to 0, while sourceEnd defaults to
Slice Buffer
• Syntax
• Following is the syntax of the method to get a sub-buffer
of a node buffer
– buf.slice([start][, end])
• Parameters
• Here is the description of the parameters used
– start − Number, Optional, Default: 0
– end − Number, Optional, Default: buffer.length
• Return Value
• Returns a new buffer which references the same memory
as the old one, but offset and cropped by the start
(defaults to 0) and end (defaults to buffer.length) indexes.
Negative indexes start from the end of the buffer.
Buffer Length
• Syntax
• Following is the syntax of the method to get a size of a
node buffer in bytes
– buf.length;
• Parameters
• Here is the description of the parameters used
– start − Number, Optional, Default: 0
– end − Number, Optional, Default: buffer.length
• Return Value
• Returns a new buffer which references the same memory
as the old one, but offset and cropped by the start
(defaults to 0) and end (defaults to buffer.length) indexes.
Negative indexes start from the end of the buffer.
Buffer Class Methods
Sr.No. Method & Description
1 Buffer.isEncoding(encoding)
Returns true if the encoding is a valid encoding argument, false otherwise.

2 Buffer.isBuffer(obj)
Tests if obj is a Buffer.

3 Buffer.byteLength(string[, encoding])
Gives the actual byte length of a string. encoding defaults to 'utf8'. It is not
the same as String.prototype.length, since String.prototype.length returns
the number of characters in a string.

4 Buffer.concat(list[, totalLength])
Returns a buffer which is the result of concatenating all the buffers in the list
together.

5 Buffer.compare(buf1, buf2)
The same as buf1.compare(buf2). Useful for sorting an array of buffers.
Buffer Methods
Method Description
alloc() Creates a Buffer object of the specified length

allocUnsafe() Creates a non-zero-filled Buffer of the specified length

allocUnsafeSlow() Creates a non-zero-filled and non-pooled Buffer of the specified


length

byteLength() Returns the numbers of bytes in a specified object

compare() Compares two Buffer objects


concat() Concatenates an array of Buffer objects into one Buffer object

copy() Copies the specified number of bytes of a Buffer object

entries() Returns an iterator of "index" "byte" pairs of a Buffer object


Buffer Methods
equals() Compares two Buffer objects, and returns true if it is a match,
otherwise false
fill() Fills a Buffer object with the specified values
from() Creates a Buffer object from an object (string/array/buffer)
includes() Checks if the Buffer object contains the specified value. Returns true if
there is a match, otherwise false

indexOf() Checks if the Buffer object contains the specified value. Returns the
first occurrence, otherwise -1

isBuffer() Checks if an object is a Buffer object


isEncoding() Checks if the Buffer object supports the specified encoding
keys() Returns an array of keys in a Buffer object
lastIndexOf() Checks if the Buffer object contains the specified value. Returns the
first occurrence, starting from the end, otherwise -1

length() Returns the length of a Buffer object, in bytes


poolSize() Sets or returns the number of bytes used for pooling
Node.js Timer
• The Timers module provides a way scheduling functions to be called
later at a given time.
• Node.js Timer functions are global functions. You don't need to use
require() function in order to use timer functions. Let's see the list of
timer functions.
• Set timer functions:
– setImmediate(): It is used to execute setImmediate.
– setInterval(): It is used to define a time interval.
– setTimeout(): It is used to execute a one-time callback after delay
milliseconds.
• Clear timer functions:
– clearImmediate(immediateObject): It is used to stop an immediateObject, as
created by setImmediate
– clearInterval(intervalObject): It is used to stop an intervalObject, as created
by setInterval
– clearTimeout(timeoutObject): It prevents a timeoutObject, as created by
Node.js Timer
Method Description
clearImmediate() Cancels an Immediate object

clearInterval() Cancels an Interval object

clearTimeout() Cancels a Timeout object

ref() Makes the Timeout object active. Will only have an effect if the
Timeout.unref() method has been called to make the Timeout object
inactive.

setImmediate() Executes a given function immediately.

setInterval() Executes a given function at every given milliseconds

setTimeout() Executes a given function after a given time (in milliseconds)

unref() Stops the Timeout object from remaining active.


Node.js - Streams
• Streams are objects that let you read data from a source or write data to a
destination in continuous fashion. In Node.js, there are four types of
streams −
– Readable − Stream which is used for read operation.
– Writable − Stream which is used for write operation.
– Duplex − Stream which can be used for both read and write operation.
– Transform − A type of duplex stream where the output is computed
based on input.
• Each type of Stream is an EventEmitter instance and throws several events
at different instance of times. For example, some of the commonly used
events are −
– data : This event is fired when there is data is available to read.
– end : This event is fired when there is no more data to read.
– error :This event is fired when there is any error receiving or writing
data.
– Finish : This event is fired when all the data has been flushed to
underlying system.
Node.js - Streams
• Reading from a Stream
• Input.txt
• Read.js
• Writing to a Stream
• Output.txt
• Write.js
Piping the Streams
• Piping is a mechanism where we provide the
output of one stream as the input to another
stream. It is normally used to get data from
one stream and to pass the output of that
stream to another stream. There is no limit on
piping operations. Now we'll show a piping
example for reading from one file and writing
it to another file.
Chaining the Streams
• Chaining is a mechanism to connect the
output of one stream to another stream and
create a chain of multiple stream operations.
It is normally used with piping operations.
Now we'll use piping and chaining to first
compress a file and then decompress the
same.
Node.js - File System
• Node implements File I/O using simple
wrappers around standard POSIX functions.
• The Node File System (fs) module can be
imported using the following syntax −
var fs = require("fs")
Node.js - File System
• Synchronous vs Asynchronous
• Every method in the fs module has synchronous as
well as asynchronous forms. Asynchronous
methods take the last parameter as the
completion function callback and the first
parameter of the callback function as error. It is
better to use an asynchronous method instead of
a synchronous method, as the former never blocks
a program during its execution, whereas the
second one does.
Open a File
• Syntax
• Following is the syntax of the method to open a file in
asynchronous mode −
fs.open(path, flags[, mode], callback)
• Parameters
• Here is the description of the parameters used −
– path − This is the string having file name including path.
– flags − Flags indicate the behavior of the file to be opened. All
possible values have been mentioned below.
– mode − It sets the file mode (permission and sticky bits), but only if
the file was created. It defaults to 0666, readable and writeable.
– callback − This is the callback function which gets two arguments
(err, fd).
Flags
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).
Flags
Flag Description

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+ open file for reading and appending. the file is created if it does not
exist.
Get File Information
• Syntax
• Following is the syntax of the method to get the
information about a file −
fs.stat(path, callback)
• Parameters
• Here is the description of the parameters used −
– Path: This is the string having file name including path.
– Callback: This is the callback function which gets two
arguments (err, stats) where stats is an object of
fs.Stats type which is printed below in the example.
Node.js fs.Stats class Methods
Method Description

stats.isfile() returns true if file type of a simple file.

stats.isdirectory() returns true if file type of a directory.

stats.isblockdevice() returns true if file type of a block device.

stats.ischaracterdevice() returns true if file type of a character device.

stats.issymboliclink() returns true if file type of a symbolic link.

stats.isfifo() returns true if file type of a fifo.

stats.issocket() returns true if file type of asocket.


Writing a File
• Syntax
• Following is the syntax of one of the methods to write
into a file −
fs.writeFile(filename, data[, options], callback)
• Parameters
• Here is the description of the parameters used −
– path − This is the string having the file name including path.
– data − This is the String or Buffer to be written into the file.
– options − The third parameter is an object which will hold
{encoding, mode, flag}. By default. encoding is utf8, mode is
octal value 0666. and flag is 'w'
– callback − This is the callback function which gets a single
parameter err that returns an error in case of any writing error.
Reading a File
• Syntax
• Following is the syntax of one of the methods to read from a
file −
fs.read(fd, buffer, offset, length, position, callback)
• Parameters
• Here is the description of the parameters used −
– fd − This is the file descriptor returned by fs.open().
– buffer − This is the buffer that the data will be written to.
– offset − This is the offset in the buffer to start writing at.
– length − This is an integer specifying the number of bytes to read.
– position − This is an integer specifying where to begin reading from
in the file. If position is null, data will be read from the current file
position.
– callback − This is the callback function which gets the three
arguments, (err, bytesRead, buffer).
Closing a File
• Syntax
• Following is the syntax of one of the methods to
close an opened file −
fs.close(fd, callback)
• Parameters
• Here is the description of the parameters used −
– fd − This is the file descriptor returned by fs.open().
– callback − This is the callback function No arguments
other than a possible exception are given to the
completion callback.
Truncate a File
• Syntax
• Following is the syntax of one of the methods to
truncate an opened file −
fs.ftruncate(fd, len, callback)
• Parameters
• Here is the description of the parameters used −
– fd − This is the file descriptor returned by fs.open().
– len − This is the length of the file after which the file will
be truncated.
– callback − This is the callback function No arguments
other than a possible exception are given to the
completion callback.
Delete a File
• Syntax
• Following is the syntax of one of the methods
to delete a file −
fs.unlink(path, callback)
• Parameters
• Here is the description of the parameters used
– path − This is the file name including path.
– callback − This is the callback function No
arguments other than a possible exception are
given to the completion callback.
Create a Directory
• Syntax
• Following is the syntax of one of the methods to
create a directory −
fs.mkdir(path[, mode], callback)
• Parameters
• Here is the description of the parameters used
– path − This is the directory name including path.
– mode − This is the directory permission to be set.
Defaults to 0777.
– callback − This is the callback function No arguments
other than a possible exception are given to the
completion callback.
Read a Directory
• Syntax
• Following is the syntax of one of the methods
to read a directory −
fs.readdir(path, callback)
• Parameters
• Here is the description of the parameters used
– path − This is the directory name including path.
– callback − This is the callback function which gets
two arguments (err, files) where files is an array of
the names of the files in the directory excluding '.'
and '..'.
Remove a Directory
• Syntax
• Following is the syntax of one of the methods
to remove a directory −
fs.rmdir(path, callback)
• Parameters
• Here is the description of the parameters used
– path − This is the directory name including path.
– callback − This is the callback function No
arguments other than a possible exception are
given to the completion callback.
Node.js - Web Module
• What is a Web Server?
• A Web Server is a software application which handles HTTP
requests sent by the HTTP client, like web browsers, and returns
web pages in response to the clients. Web servers usually deliver
html documents along with images, style sheets, and scripts.
• Most of the web servers support server-side scripts, using
scripting languages or redirecting the task to an application
server which retrieves data from a database and performs
complex logic and then sends a result to the HTTP client through
the Web server.
• Apache web server is one of the most commonly used web
servers. It is an open source project.
Web Application Architecture
• A Web application is usually divided into four layers −

• Client − This layer consists of web browsers, mobile browsers or applications which
can make HTTP requests to the web server.
• Server − This layer has the Web server which can intercept the requests made by
the clients and pass them the response.
• Business − This layer contains the application server which is utilized by the web
server to do the required processing. This layer interacts with the data layer via the
database or some external programs.
Creating a Web Server using Node
• Node.js provides an http module which can be
used to create an HTTP client of a server.
• Following is the bare minimum structure of
the HTTP server which listens at 8081 port.
• Create server and index.html
Creating Web client using Node
• A web client can be created
using http module. Let's check the following
example.
ExpressJS - Overview
• ExpressJS is a web application framework that
provides you with a simple API to build
websites, web apps and back ends. With
ExpressJS, you need not worry about low level
protocols, processes, etc.
What is Express?
• Express provides a minimal interface to build our
applications. It provides us the tools that are
required to build our app. It is flexible as there
are numerous modules available on npm, which
can be directly plugged into Express.
• Express was developed by TJ Holowaychuk and is
maintained by the Node.js foundation and
numerous open source contributors.
Why Express?
• Unlike its competitors like Rails and Django, which have an
opinionated way of building applications, Express has no
"best way" to do something. It is very flexible and pluggable.
• Pug
• Pug (earlier known as Jade) is a terse language for writing
HTML templates. It −
• Produces HTML
• Supports dynamic code
• Supports reusability (DRY)
• It is one of the most popular template language used with
Express.
ExpressJS - Environment
• node --version npm --version You should get an output similar to the following.
• v5.0.0 3.5.2 Now that we have Node and npm set up, let us understand what npm is and how
to use it.
• Node Package Manager(npm)
• npm is the package manager for node. The npm Registry is a public collection of packages of
open-source code for Node.js, front-end web apps, mobile apps, robots, routers, and countless
other needs of the JavaScript community. npm allows us to access all these packages and install
them locally. You can browse through the list of packages available on npm at npmJS.
• How to use npm?
• There are two ways to install a package using npm: globally and locally.
• Globally − This method is generally used to install development tools and CLI based packages.
To install a package globally, use the following code.
• npm install -g <package-name>
• Locally − This method is generally used to install frameworks and libraries. A locally installed
package can be used only within the directory it is installed. To install a package locally, use the
same command as above without the -g flag.
• npm install <package-name>
• Whenever we create a project using npm, we need to provide a package.json file, which has all
the details about our project. npm makes it easy for us to set up this file. Let us set up our
development project.
• Step 1 − Start your terminal/cmd, create a new folder named hello-world and cd (create
ExpressJS - Environment
• Step 2 − Now to create the package.json file using npm, use the following code.
• npm init
• Step 3 − Now we have our package.json file set up, we will further install Express. To
install Express and add it to our package.json file, use the following command −
• npm install --save express
• To confirm that Express has installed correctly, run the following code.
• ls node_modules #(dir node_modules for windows)
• Tip − The --save flag can be replaced by the -S flag.
• This flag ensures that Express is added as a dependency to our package.json file.
This has an advantage, the next time we need to install all the dependencies of our
project we can just run the command npm install and it will find the dependencies
in this file and install them for us.
• This is all we need to start development using the Express framework. To make our
development process a lot easier, we will install a tool from npm, nodemon. This
tool restarts our server as soon as we make a change in any of our files, otherwise
we need to restart the server manually after each file modification. To install
nodemon, use the following command −
• npm install -g nodemon
ExpressJS - Hello World
• We have set up the development, now it is
time to start developing our first app using
Express. Create a new file called index.js and
type the following in it.
• Save the file, go to your terminal and type the
following. var express = require('express');
var app = express();
• nodemon index.js app.get('/', function(req, res){
res.send("Hello
world!");
});
app.listen(3000);
How the App Works?
• The first line imports Express in our file, we have access to it through the variable Express. We use it to
create an application and assign it to var app.
• app.get(route, callback)
• This function tells what to do when a get request at the given route is called. The callback function has 2
parameters, request(req) and response(res). The request object(req) represents the HTTP request and
has properties for the request query string, parameters, body, HTTP headers, etc. Similarly, the response
object represents the HTTP response that the Express app sends when it receives an HTTP request.
• res.send()
• This function takes an object as input and it sends this to the requesting client. Here we are sending the
string "Hello World!".
• app.listen(port, [host], [backlog], [callback]])
• This function binds and listens for connections on the specified host and port. Port is the only required
parameter here.
– port
• A port number on which the server should accept incoming requests.
– host
• Name of the domain. You need to set it when you deploy your apps to the cloud.
– backlog
• The maximum number of queued pending connections. The default is 511.
– callback
• An asynchronous function that is called when the server starts listening for requests.
Node.js - RESTful API
• What is REST architecture?
• REST stands for REpresentational State Transfer. REST is web
standards based architecture and uses HTTP Protocol. It
revolves around resource where every component is a resource
and a resource is accessed by a common interface using HTTP
standard methods. REST was first introduced by Roy Fielding
in 2000.
• A REST Server simply provides access to resources and REST
client accesses and modifies the resources using HTTP
protocol. Here each resource is identified by URIs/ global IDs.
REST uses various representation to represent a resource like
text, JSON, XML but JSON is the most popular one.
HTTP methods
• Following four HTTP methods are commonly
used in REST based architecture.
– GET − This is used to provide a read only access to
a resource.
– PUT − This is used to create a new resource.
– DELETE − This is used to remove a resource.
– POST − This is used to update a existing resource
or create a new resource.
RESTful Web Services
• A web service is a collection of open protocols and standards used
for exchanging data between applications or systems. Software
applications written in various programming languages and
running on various platforms can use web services to exchange
data over computer networks like the Internet in a manner similar
to inter-process communication on a single computer. This
interoperability (e.g., communication between Java and Python,
or Windows and Linux applications) is due to the use of open
standards.
• Web services based on REST Architecture are known as RESTful
web services. These webservices uses HTTP methods to
implement the concept of REST architecture. A RESTful web
service usually defines a URI, Uniform Resource Identifier a
service, which provides resource representation such as JSON and
set of HTTP Methods.
Creating RESTful for A Library
• Consider we have a JSON based database of users
having the following users in a file users.json
• Based on this information we are going to provide
following RESTful APIs.
Sr.No. URI HTTP Method POST body Result

1 listUsers GET empty Show list of all the users.

2 addUser POST JSON String Add details of new user.

3 deleteUser DELETE JSON String Delete an existing user.

4 :id GET empty Show details of a user.


List Users
• Let's implement our first RESTful
API listUsers using the following code in a
server.js file.
Show Detail

• Now we will implement an API which will be


called using user ID and it will display the
detail of the corresponding user.
Delete User

• This API is very similar to addUser API where


we receive input data through req.body and
then based on user ID we delete that user
from the database. To keep our program
simple we assume we are going to delete user
with ID 2.
ExpressJS - Sessions
• HTTP is stateless; in order to associate a request to any other request, you
need a way to store user data between HTTP requests. Cookies and URL
parameters are both suitable ways to transport data between the client and
the server. But they are both readable and on the client side. Sessions solve
exactly this problem. You assign the client an ID and it makes all further
requests using that ID. Information associated with the client is stored on the
server linked to this ID.
• We will need the Express-session, so install it using the following code.
• npm install --save express-session
• We will put the session and cookie-parser middleware in place. In this
example, we will use the default store for storing sessions, i.e., MemoryStore.
Never use this in production environments. The session middleware handles all
things for us, i.e., creating the session, setting the session cookie and creating
the session object in req object.
• Whenever we make a request from the same client again, we will have their
session information stored with us (given that the server was not restarted).
We can add more properties to the session object. In the following example,
we will create a view counter for a client.
ExpressJS - Cookies
• Cookies are simple, small files/data that are sent to client with a server request
and stored on the client side. Every time the user loads the website back, this
cookie is sent with the request. This helps us keep track of the user’s actions.
• The following are the numerous uses of the HTTP Cookies −
• Session management
• Personalization(Recommendation systems)
• User tracking
• To use cookies with Express, we need the cookie-parser middleware. To install
it, use the following code −
• npm install --save cookie-parser Now to use cookies with Express, we will
require the cookie-parser. cookie-parser is a middleware which parses cookies
attached to the client request object. To use it, we will require it in
our index.js file; this can be used the same way as we use other middleware.
Here, we will use the following code.
var cookieParser = require('cookie-parser');
app.use(cookieParser());
ExpressJS - Cookies
• cookie-parser parses Cookie header and populates req.cookies with an object keyed by the cookie
names. To set a new cookie, let us define a new route in your Express app like −
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.cookie('name', 'express').send('cookie set');
//Sets name = express
});
app.listen(3000);
• To check if your cookie is set or not, just go to your browser, fire up the console, and enter −
console.log(document.cookie);
• You will get the output like (you may have more cookies set maybe due to extensions in your
browser) −
"name = express"
• The browser also sends back cookies every time it queries the server. To view cookies from your
server, on the server console in a route, add the following code to that route.
console.log('Cookies: ', req.cookies);
• Next time you send a request to this route, you will receive the following output.
Cookies: { name: 'express' }
Adding Cookies with Expiration Time
• You can add cookies that expire. To add a cookie that
expires, just pass an object with property 'expire' set
to the time when you want it to expire. For example,
• //Expires after 360000 ms from the time it is set.
res.cookie(name, 'value', {expire: 360000 +
Date.now()});
• Another way to set expiration time is
using 'maxAge' property. Using this property, we can
provide relative time instead of absolute time.
Following is an example of this method.
• //This cookie also expires after 360000 ms from the
time it is
Deleting Existing Cookies
• To delete a cookie, use the clearCookie
function. For example, if you need to clear a
cookie named foo, use the following code.

var express = require('express');


var app = express();
app.get('/clear_cookie_foo', function(req, res)
{
res.clearCookie('foo');
res.send('cookie foo cleared');
});
app.listen(3000);
ExpressJS - Debugging
• Express uses the Debug module to internally log information
about route matching, middleware functions, application mode,
etc.
• To see all internal logs used in Express, set the DEBUG
environment variable to Express:* when starting the app −
• DEBUG = express:* node index.js
• These logs are very helpful when a component of your app is not
functioning right. This verbose output might be a little
overwhelming. You can also restrict the DEBUG variable to
specific area to be logged. For example, if you wish to restrict the
logger to application and router, you can use the following code.
• DEBUG = express:application,express:router node index.js
• Debug is turned off by default and is automatically turned on in
production environment. Debug can also be extended to meet

You might also like