Nodejs Tutorial PDF
Nodejs Tutorial PDF
js
i
Node.js
Audience
This tutorial is designed for software programmers who want to learn the basics
of Node.js and its architectural concepts. This tutorial will give you enough
understanding on all the necessary components of Node.js with suitable examples.
Prerequisites
Before proceeding with this tutorial, you should have a basic understanding of
JavaScript. As we are going to develop web-based applications using Node.js, it
will be good if you have some understanding of other web technologies such as
HTML, CSS, AJAX, etc.
Try the following example using the Try it option available at the top right corner
of the below sample code box (on our website):
i
Node.js
All the content and graphics published in this e-book are the property of Tutorials
Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy,
distribute or republish any contents or a part of contents of this e-book in any
manner without written consent of the publisher.
We strive to update the contents of our website and tutorials as timely and as
precisely as possible, however, the contents may contain inaccuracies or errors.
Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy,
timeliness or completeness of our website or its contents including this tutorial. If
you discover any errors on our website or in this tutorial, please notify us at
contact@tutorialspoint.com
ii
Node.js
Table of Contents
About the Tutorial ............................................................................................................................................ i
Audience ........................................................................................................................................................... i
Prerequisites ..................................................................................................................................................... i
Execute Node.js Online..................................................................................................................................... i
Copyright & Disclaimer .................................................................................................................................... ii
Table of Contents ........................................................................................................................................... iii
1. Introduction .............................................................................................................................................. 1
What is Node.js? .............................................................................................................................................. 1
Features of Node.js ......................................................................................................................................... 1
Who Uses Node.js? .......................................................................................................................................... 2
Concepts .......................................................................................................................................................... 2
Where to Use Node.js? .................................................................................................................................... 3
Where Not to Use Node.js? ............................................................................................................................. 3
5. NPM........................................................................................................................................................ 14
Installing Modules using NPM ....................................................................................................................... 14
Global vs Local Installation ............................................................................................................................ 14
Using package.json ........................................................................................................................................ 16
Attributes of Package.json ............................................................................................................................. 21
Uninstalling a Module ................................................................................................................................... 21
Updating a Module ........................................................................................................................................ 22
Search a Module ............................................................................................................................................ 22
Create a Module ............................................................................................................................................ 22
iii
Node.js
9. Buffers .................................................................................................................................................... 35
Creating Buffers ............................................................................................................................................. 35
Writing to Buffers .......................................................................................................................................... 35
Reading from Buffers ..................................................................................................................................... 36
Convert Buffer to JSON .................................................................................................................................. 37
Concatenate Buffers ...................................................................................................................................... 38
Compare Buffers ............................................................................................................................................ 39
Copy Buffer .................................................................................................................................................... 39
Slice Buffer..................................................................................................................................................... 40
Buffer Length ................................................................................................................................................. 41
Methods Reference ....................................................................................................................................... 42
Class Methods ............................................................................................................................................... 50
10. Streams................................................................................................................................................... 51
What are Streams? ........................................................................................................................................ 51
Reading from a Stream .................................................................................................................................. 51
Writing to a Stream ....................................................................................................................................... 52
Piping the Streams......................................................................................................................................... 53
Chaining the Streams..................................................................................................................................... 54
iv
Node.js
v
Node.js
1. INTRODUCTION
What is Node.js?
Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8
Engine). Node.js was developed by Ryan Dahl in 2009 and its latest version is
v0.10.36. The definition of Node.js as supplied by its official documentation is as
follows:
Node.js also provides a rich library of various JavaScript modules which simplifies
the development of web applications using Node.js to a great extent.
Features of Node.js
Following are some of the important features that make Node.js the first choice of
software architects.
1
Node.js
Concepts
The following diagram depicts some important parts of Node.js which we will
discuss in detail in the subsequent chapters.
2
Node.js
3
Node.js
2. ENVIRONMENT SETUP
Try the following example using the Try it option available at the top right corner
of the below sample code box (on our website):
For most of the examples given in this tutorial, you will find a Try it option, so just
make use of it and enjoy your learning.
Text Editor
You need to have a text editor to type your program. Examples of text editors
include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or
vi.
The name and version of text editors can vary from one operating system to
another. For example, Notepad will be used on Windows, and vim or vi can be
used on Windows as well as Linux or UNIX.
The files you create with your editor are called source files and they contain the
program source code. The source files for Node.js programs are typically named
with the extension ".js".
Before you start programming, make sure you have one text editor in place and
you have enough experience in how to write a computer program, save it in a file,
and finally execute it.
4
Node.js
Node.js distribution comes as a binary installable for SunOS, Linux, Mac OS X, and
Windows operating systems with the 32-bit (386) and 64-bit (amd64) x86
processor architectures.
The following section explains how to install Node.js binary distribution on various
OS.
OS Archive name
Windows node-v0.12.0-x64.msi
Linux node-v0.12.0-linux-x86.tar.gz
Mac node-v0.12.0-darwin-x86.tar.gz
SunOS node-v0.12.0-sunos-x86.tar.gz
$ cd /tmp
$ wget http://nodejs.org/dist/v0.12.0/node-v0.12.0-linux-x64.tar.gz
$ tar xvfz node-v0.12.0-linux-x64.tar.gz
$ mkdir -p /usr/local/nodejs
$ mv node-v0.12.0-linux-x64/* /usr/local/nodejs
5
Node.js
OS Output
Installation on Windows
Use the MSI file and follow the prompts to install Node.js. By default, the installer
uses the Node.js distribution in C:\Program Files\nodejs. The installer should set
the C:\Program Files\nodejs\bin directory in Window's PATH environment
variable. Restart any open command prompts for the change to take effect.
$ node main.js
If everything is fine with your installation, it should produce the following result:
Hello, World!
6
Node.js
3. FIRST APPLICATION
Before creating an actual "Hello, World!" application using Node.js, let us see the
components of a Node.js application. A Node.js application consists of the
following three important components:
3. Read request and return response: The server created in an earlier step
will read the HTTP request made by the client which can be a browser or a
console and return the response.
7
Node.js
}).listen(8081);
The above code is enough to create an HTTP server which listens, i.e., waits for a
request over 8081 port on the local machine.
$ node main.js
8
Node.js
Congratulations, you have your first HTTP server up and running which is
responding to all the HTTP requests at port 8081.
9
Node.js
4. REPL TERMINAL
REPL stands for Read Eval Print Loop and it represents a computer environment
like a Windows console or Unix/Linux shell where a command is entered and the
system responds with an output in an interactive mode. Node.js or Node comes
bundled with a REPL environment. It performs the following tasks:
Read - Reads user's input, parses the input into JavaScript data-structure,
and stores in memory.
Loop - Loops the above command until the user presses ctrl-c twice.
The REPL feature of Node is very useful in experimenting with Node.js codes and
to debug JavaScript codes.
Starting REPL
REPL can be started by simply running node on shell/console without any
arguments as follows.
$ node
You will see the REPL Command prompt > where you can type any Node.js
command:
$ node
>
Simple Expression
Let's try a simple mathematics at the Node.js REPL command prompt:
$ node
> 1 + 3
10
Node.js
4
> 1 + ( 2 * 3 ) - 4
3
>
Use Variables
You can make use variables to store values and print later like any conventional
script. If var keyword is not used, then the value is stored in the variable and
printed. Whereas if var keyword is used, then the value is stored but not printed.
You can print variables using console.log().
$ node
> x = 10
10
> var y = 10
undefined
> x + y
20
> console.log("Hello World")
Hello Workd
undefined
Multiline Expression
Node REPL supports multiline expression similar to JavaScript. Let's check the
following do-while loop in action:
$ node
> var x = 0
undefined
> do {
... x++;
... console.log("x: " + x);
... } while ( x < 5 );
x: 1
x: 2
x: 3
11
Node.js
x: 4
x: 5
undefined
>
... comes automatically when you press Enter after the opening bracket. Node
automatically checks the continuity of expressions.
Underscore Variable
You can use underscore (_) to get the last result:
$ node
> var x = 10
undefined
> var y = 20
undefined
> x + y
30
> var sum = _
undefined
> console.log(sum)
30
undefined
>
REPL Commands
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.
12
Node.js
Stopping REPL
As mentioned above, you will need to use ctrl-c twice to come out of Node.js
REPL.
$ node
>
(^C again to quit)
>
13
Node.js
5. NPM
NPM comes bundled with Node.js installables after v0.6.3 version. To verify the
same, open console and type the following command and see the result:
$ npm --version
2.7.1
If you are running an old version of NPM, then it is quite easy to update it to the
latest version. Just use the following command from root:
For example, following is the command to install a famous Node.js web framework
module called express:
14
Node.js
$ ls -l
total 0
drwxr-xr-x 3 root root 20 Mar 17 02:23 node_modules
Alternatively, you can use npm ls command to list down all the locally installed
modules.
This will produce a similar result but the module will be installed globally. Here,
the first line shows the module version and the location where it is getting
installed.
express@4.12.2 /usr/lib/node_modules/express
merge-descriptors@1.0.0
utils-merge@1.0.0
cookie-signature@1.0.6
methods@1.1.1
fresh@0.2.4
cookie@0.1.2
escape-html@1.0.1
range-parser@1.0.2
content-type@1.0.1
finalhandler@0.3.3
vary@1.0.0
parseurl@1.3.0
content-disposition@0.5.0
path-to-regexp@0.1.3
depd@1.0.0
qs@2.3.3
on-finished@2.2.0 (ee-first@1.1.0)
etag@1.5.1 (crc@3.2.1)
debug@2.1.3 (ms@0.7.0)
15
Node.js
You can use the following command to check all the modules installed globally:
$ npm ls -g
Using package.json
package.json is present in the root directory of any Node application/module and
is used to define the properties of a package. Let's open package.json of express
package present in node_modules/express/
{
"name": "express",
"description": "Fast, unopinionated, minimalist web framework",
"version": "4.11.2",
"author": {
"name": "TJ Holowaychuk",
"email": "tj@vision-media.ca"
},
"contributors": [
{
"name": "Aaron Heckmann",
"email": "aaron.heckmann+github@gmail.com"
},
{
"name": "Ciaran Jessup",
"email": "ciaranj@gmail.com"
},
{
"name": "Douglas Christopher Wilson",
"email": "doug@somethingdoug.com"
},
{
16
Node.js
17
Node.js
"content-disposition": "0.5.0",
"cookie-signature": "1.0.5",
"debug": "~2.1.1",
"depd": "~1.0.0",
"escape-html": "1.0.1",
"etag": "~1.5.1",
"finalhandler": "0.3.3",
"fresh": "0.2.4",
"media-typer": "0.3.0",
"methods": "~1.1.1",
"on-finished": "~2.2.0",
"parseurl": "~1.3.0",
"path-to-regexp": "0.1.3",
"proxy-addr": "~1.0.6",
"qs": "2.3.3",
"range-parser": "~1.0.2",
"send": "0.11.1",
"serve-static": "~1.8.1",
"type-is": "~1.5.6",
"vary": "~1.0.0",
"cookie": "0.1.2",
"merge-descriptors": "0.0.2",
"utils-merge": "1.0.0"
},
"devDependencies": {
"after": "0.8.1",
"ejs": "2.1.4",
"istanbul": "0.3.5",
"marked": "0.3.3",
"mocha": "~2.1.0",
"should": "~4.6.2",
"supertest": "~0.15.0",
"hjs": "~0.0.6",
"body-parser": "~1.11.0",
"connect-redis": "~2.2.0",
18
Node.js
"cookie-parser": "~1.3.3",
"express-session": "~1.10.2",
"jade": "~1.9.1",
"method-override": "~2.3.1",
"morgan": "~1.5.1",
"multiparty": "~4.1.1",
"vhost": "~3.0.0"
},
"engines": {
"node": ">= 0.10.0"
},
"files": [
"LICENSE",
"History.md",
"Readme.md",
"index.js",
"lib/"
],
"scripts": {
"test": "mocha --require test/support/env --reporter spec --bail
check-leaks test/ test/acceptance/",
19
Node.js
"url": "https://github.com/strongloop/express/issues"
},
"_id": "express@4.11.2",
"_shasum": "8df3d5a9ac848585f00a0777601823faecd3b148",
"_from": "express@*",
"_npmVersion": "1.4.28",
"_npmUser": {
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
"maintainers": [
{
"name": "tjholowaychuk",
"email": "tj@vision-media.ca"
},
{
"name": "jongleberry",
"email": "jonathanrichardong@gmail.com"
},
{
"name": "shtylman",
"email": "shtylman@gmail.com"
},
{
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
{
"name": "aredridel",
"email": "aredridel@nbtsc.org"
},
{
"name": "strongloop",
"email": "callback@strongloop.com"
},
20
Node.js
{
"name": "rfeng",
"email": "enjoyjava@gmail.com"
}
],
"dist": {
"shasum": "8df3d5a9ac848585f00a0777601823faecd3b148",
"tarball": "http://registry.npmjs.org/express/-/express-4.11.2.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/express/-/express-4.11.2.tgz",
"readme": "ERROR: No README data found!"
}
Attributes of Package.json
name - name of the package
keywords - keywords
Uninstalling a Module
Use the following command to uninstall a Node.js module.
21
Node.js
Once NPM uninstalls the package, you can verify it by looking at the content of
/node_modules/ directory or type the following command:
$ npm ls
Updating a Module
Update package.json and change the version of the dependency to be updated
and run the following command.
Search a Module
Search a package name using NPM.
Create a Module
Creating a module requires package.json to be generated. Let's generate
package.json using NPM, which will generate the basic skeleton of the
package.json.
$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sane defaults.
You will need to provide all the required information about your module. You can
take help from the above-mentioned package.json file to understand the meanings
of various information demanded. Once package.json is generated, use the
following command to register yourself with NPM repository site using a valid email
address.
22
Node.js
$ npm adduser
Username: mcmohd
Password:
Email: (this IS public) mcmohd@gmail.com
$ npm publish
If everything is fine with your module, then it will be published in the repository
and will be accessible to install using NPM like any other Node.js module.
23
Node.js
6. CALLBACK CONCEPT
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 a 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.
var fs = require("fs");
console.log(data.toString());
console.log("Program Ended");
$ node main.js
24
Node.js
var fs = require("fs");
console.log("Program Ended");
$ node main.js
Program Ended
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
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.
25
Node.js
7. EVENT LOOP
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.
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:
26
Node.js
// Fire an event
eventEmitter.emit('eventName');
Example
Create a js file named main.js with the following code:
27
Node.js
console.log("Program Ended.");
Now let's try to run the above program and check its output:
$ mnode main.js
connection successful.
data received successfully.
Program Ended.
var fs = require("fs");
28
Node.js
corresponding error, else data will contain the contents of the file. readFile passes
err and data to the callback function after the read operation is complete, which
finally prints the content.
Program Ended
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
29
Node.js
8. 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.
EventEmitter Class
As we have seen in the previous section, EventEmitter class lies in the events
module. It is accessible via the following code:
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.
Methods
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.
1
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.
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.
2
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.
30
Node.js
once(event, listener)
Adds a one-time listener to the event. This listener is invoked only the
3
next time the event is fired, after which it is removed. Returns emitter,
so calls can be chained.
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
4
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.
removeAllListeners([event])
Removes all listeners, or those of the specified event. It's not a good
5 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.
setMaxListeners(n)
By default, EventEmitters will print a warning if more than 10 listeners
6 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.
listeners(event)
7
Returns an array of listeners for the specified event.
31
Node.js
Class Methods
listenerCount(emitter, event)
1
Returns the number of listeners for a given event.
Events
newListener
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.
removeListener
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.
Example
Create a js file named main.js with the following Node.js code:
32
Node.js
// listener #1
var listner1 = function listner1() {
console.log('listner1 executed.');
}
// listener #2
var listner2 = function listner2() {
console.log('listner2 executed.');
}
var eventListeners =
require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log(eventListeners + " Listner(s) listening to connection event");
eventListeners =
require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log(eventListeners + " Listner(s) listening to connection event");
33
Node.js
console.log("Program Ended.");
$ node main.js
34
Node.js
9. 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.
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:
Method 2
Following is the syntax to create a Buffer from a given array:
Method 3
Following is the syntax to create a Buffer from a given string and optionally
encoding type:
Though "utf8" is the default encoding, you can use any of the following encodings
"ascii", "utf8", "utf16le", "ucs2", "base64" or "hex".
Writing to Buffers
Syntax
Following is the syntax of the method to write into a Node Buffer:
35
Node.js
Parameters
Here is the description of the parameters used:
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 part of the string.
Example
buf = new Buffer(256);
len = buf.write("Simply Easy Learning");
Octets written : 20
Syntax
Following is the syntax of the method to read data from a Node Buffer:
Parameters
Here is the description of the parameters used:
36
Node.js
Return Value
This method decodes and returns a string from buffer data encoded using the
specified character set encoding.
Example
buf = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
buf[i] = i + 97;
}
console.log( buf.toString('ascii'));
// outputs: abcdefghijklmnopqrstuvwxyz
console.log( buf.toString('ascii',0,5));
// outputs: abcde
console.log( buf.toString('utf8',0,5));
// outputs: abcde
console.log( buf.toString(undefined,0,5));
// encoding defaults to 'utf8', outputs abcde
abcdefghijklmnopqrstuvwxyz
abcde
abcde
abcde
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.
37
Node.js
Example
var buf = new Buffer('Simply Easy Learning');
var json = buf.toJSON(buf);
console.log(json);
[ 83, 105, 109, 112, 108, 121, 32, 69, 97, 115, 121, 32, 76, 101, 97,
114, 110, 105, 110, 103 ]
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:
Return Value
This method returns a Buffer instance.
Example
var buffer1 = new Buffer('TutorialsPoint ');
var buffer2 = new Buffer('Simply Easy Learning');
var buffer3 = Buffer.concat([buffer1,buffer2]);
console.log("buffer3 content: " + buffer3.toString());
38
Node.js
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 sort order.
Example
var buffer1 = new Buffer('ABC');
var buffer2 = new Buffer('ABCD');
var result = buffer1.compare(buffer2);
if(result < 0) {
console.log(buffer1 +" comes before " + buffer2);
}else if(result == 0){
console.log(buffer1 +" is same as " + buffer2);
}else {
console.log(buffer1 +" comes after " + buffer2);
}
Copy Buffer
Syntax
Following is the syntax of the method to copy a node buffer:
39
Node.js
Parameters
Here is the description of the parameters used:
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 buffer.length.
Example
var buffer1 = new Buffer('ABC');
//copy a buffer
var buffer2 = new Buffer(3);
buffer1.copy(buffer2);
console.log("buffer2 content: " + buffer2.toString());
Slice Buffer
Syntax
Following is the syntax of the method to get a sub-buffer of a node buffer:
buf.slice([start][, end])
40
Node.js
Parameters
Here is the description of the parameters used:
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.
Example
var buffer1 = new Buffer('TutorialsPoint');
//slicing a buffer
var buffer2 = buffer1.slice(0,9);
console.log("buffer2 content: " + buffer2.toString());
Buffer Length
Syntax
Following is the syntax of the method to get a size of a node buffer in bytes:
buf.length;
Return Value
Returns the size of a buffer in bytes.
Example
var buffer = new Buffer('TutorialsPoint');
//length of the buffer
console.log("buffer length: " + buffer.length);
41
Node.js
buffer length: 14
Methods Reference
Following is a reference of Buffers module available in Node.js. For more detail,
you can refer to the official documentation.
new Buffer(size)
1 Allocates a new buffer of size octets. Note that the size must be no
more than kMaxLength. Otherwise, a RangeError will be thrown here.
new Buffer(buffer)
2
Copies the passed buffer data onto a new Buffer instance.
buf.length
Returns the size of the buffer in bytes. Note that this is not necessarily
4 the size of the contents. length refers to the amount of memory
allocated for the buffer object. It does not change when the contents of
the buffer are changed.
42
Node.js
43
Node.js
buf.toJSON()
15 Returns a JSON-representation of the Buffer instance. JSON.stringify
implicitly calls this function when stringifying a Buffer instance.
buf[index]
16 Get and set the octet at index. The values refer to individual bytes, so
the legal range is between 0x00 and 0xFF hex or 0 and 255.
buf.equals(otherBuffer)
17
Returns a boolean if this buffer and otherBuffer have the same bytes.
buf.compare(otherBuffer)
18 Returns a number indicating whether this buffer comes before or after
or is the same as the otherBuffer in sort order.
buf.slice([start][, end])
Returns a new buffer which references the same memory as the old,
20 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.
buf.readUInt8(offset[, noAssert])
Reads an unsigned 8-bit integer from the buffer at the specified offset.
21
Set noAssert to true to skip validation of offset. It means the offset
may be beyond the end of the buffer. Defaults to false.
22 buf.readUInt16LE(offset[, noAssert])
Reads an unsigned 16-bit integer from the buffer at the specified offset
44
Node.js
with the specified endian format. Set noAssert to true to skip validation
of offset. It means the offset may be beyond the end of the buffer.
Defaults to false.
buf.readUInt16BE(offset[, noAssert])
Reads an unsigned 16-bit integer from the buffer at the specified offset
23 with the specified endian format. Set noAssert to true to skip validation
of offset. It means the offset may be beyond the end of the buffer.
Defaults to false.
buf.readUInt32LE(offset[, noAssert])
Reads an unsigned 32-bit integer from the buffer at the specified offset
24 with the specified endian format. Set noAssert to true to skip validation
of offset. It means the offset may be beyond the end of the buffer.
Defaults to false.
buf.readUInt32BE(offset[, noAssert])
Reads an unsigned 32-bit integer from the buffer at the specified offset
25 with the specified endian format. Set noAssert to true to skip validation
of offset. It means the offset may be beyond the end of the buffer.
Defaults to false.
buf.readInt8(offset[, noAssert])
Reads a signed 8-bit integer from the buffer at the specified offset. Set
26
noAssert to true to skip validation of offset. It means the offset may be
beyond the end of the buffer. Defaults to false.
buf.readInt16LE(offset[, noAssert])
Reads a signed 16-bit integer from the buffer at the specified offset
27 with the specified endian format. Set noAssert to true to skip validation
of offset. It means the offset may be beyond the end of the buffer.
Defaults to false.
buf.readInt16BE(offset[, noAssert])
Reads a signed 16-bit integer from the buffer at the specified offset
28 with the specified endian format. Set noAssert to true to skip validation
of offset. It means the offset may be beyond the end of the buffer.
Defaults to false.
45
Node.js
buf.readInt32LE(offset[, noAssert])
Reads a signed 32-bit integer from the buffer at the specified offset
29 with the specified endian format. Set noAssert to true to skip validation
of offset. It means the offset may be beyond the end of the buffer.
Defaults to false.
buf.readInt32BE(offset[, noAssert])
Reads a signed 32-bit integer from the buffer at the specified offset
30 with the specified endian format. Set noAssert to true to skip validation
of offset. It means the offset may be beyond the end of the buffer.
Defaults to false.
buf.readFloatLE(offset[, noAssert])
Reads a 32-bit float from the buffer at the specified offset with the
31 specified endian format. Set noAssert to true to skip validation of
offset. It means the offset may be beyond the end of the buffer.
Defaults to false.
buf.readFloatBE(offset[, noAssert])
Reads a 32-bit float from the buffer at the specified offset with the
32 specified endian format. Set noAssert to true to skip validation of
offset. It means the offset may be beyond the end of the buffer.
Defaults to false.
buf.readDoubleLE(offset[, noAssert])
Reads a 64-bit double from the buffer at the specified offset with the
33 specified endian format. Set noAssert to true to skip validation of
offset. It means the offset may be beyond the end of the buffer.
Defaults to false.
buf.readDoubleBE(offset[, noAssert])
Reads a 64-bit double from the buffer at the specified offset with the
34 specified endian format. Set noAssert to true to skip validation of
offset. It means the offset may be beyond the end of the buffer.
Defaults to false.
46
Node.js
the specific function and offset may be beyond the end of the buffer
leading to the values being silently dropped. It should not be used
unless you are certain of its correctness. Defaults to false.
47
Node.js
48
Node.js
means the value may be too large for the specific function and the
offset may be beyond the end of the buffer leading to the values being
silently dropped. It should not be used unless you are certain of
correctness. Defaults to false.
49
Node.js
end (defaults to buffer.length) are not given, it will fill the entire
buffer.
Class Methods
Buffer.isEncoding(encoding)
1 Returns true if the encoding is a valid encoding argument, false
otherwise.
Buffer.isBuffer(obj)
2
Tests if obj is a Buffer.
Buffer.byteLength(string[, encoding])
Gives the actual byte length of a string. encoding defaults to 'utf8'. It
3
is not the same as String.prototype.length, since
String.prototype.length returns the number of characters in a string.
Buffer.concat(list[, totalLength])
4 Returns a buffer which is the result of concatenating all the buffers in
the list together.
Buffer.compare(buf1, buf2)
5 The same as buf1.compare(buf2). Useful for sorting an array of
buffers.
50
Node.js
10. STREAMS
Duplex - Stream which can be used for both read and write operation.
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.
var fs = require("fs");
var data = '';
51
Node.js
readerStream.on('end',function(){
console.log(data);
});
readerStream.on('error', function(err){
console.log(err.stack);
});
console.log("Program Ended");
$ node main.js
Program Ended
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Writing to a Stream
Create a js file named main.js with the following code:
var fs = require("fs");
var data = 'Simply Easy Learning';
52
Node.js
writerStream.on('error', function(err){
console.log(err.stack);
});
console.log("Program Ended");
$ node main.js
Program Ended
Write completed.
Now open output.txt created in your current directory; it should contain the
following:
53
Node.js
var fs = require("fs");
console.log("Program Ended");
$ node main.js
Program Ended
Open output.txt created in your current directory; it should contain the following:
var fs = require("fs");
var zlib = require('zlib');
54
Node.js
fs.createReadStream('input.txt')
.pipe(zlib.createGzip())
.pipe(fs.createWriteStream('input.txt.gz'));
console.log("File Compressed.");
$ node main.js
File Compressed.
You will find that input.txt has been compressed and it created a file input.txt.gz
in the current directory. Now let's try to decompress the same file using the
following code:
var fs = require("fs");
var zlib = require('zlib');
console.log("File Decompressed.");
$ node main.js
File Decompressed.
55
Node.js
11. 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:
ar fs = require("fs")
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.
Example
Create a text file named input.txt with the following content:
var fs = require("fs");
// Asynchronous read
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
// Synchronous read
var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());
56
Node.js
console.log("Program Ended");
$ node main.js
Program Ended
Asynchronous read: Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
The following sections in this chapter provide a set of good examples on major
File I/O methods.
Open a File
Syntax
Following is the syntax of the method to open a file in asynchronous mode:
Parameters
Here is the description of the parameters used:
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).
57
Node.js
Flags
Flags for read/write operations are:
Flag Description
r Open file for reading. An exception occurs if the file does not exist.
Open file for reading and writing. An exception occurs if the file does not
r+
exist.
Open file for reading and writing, asking the OS to open it synchronously.
rs+
See notes for 'rs' about using this with caution.
Open file for writing. The file is created (if it does not exist) or truncated
w
(if it exists).
Open file for reading and writing. The file is created (if it does not exist)
w+
or truncated (if it exists).
a Open file for appending. The file is created if it does not exist.
a+ Open file for reading and appending. The file is created if it does not exist.
Example
Let us create a js file named main.js having the following code to open a file
input.txt for reading and writing.
var fs = require("fs");
58
Node.js
$ node main.js
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:
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.
Apart from the important attributes which are printed below in the example, there
are several useful methods available in fs.Stats class which can be used to check
file type. These methods are given in the following table.
59
Node.js
Method Description
Example
Let us create a js file named main.js with the following code:
var fs = require("fs");
60
Node.js
$ node main.js
Writing a File
Syntax
Following is the syntax of one of the methods to write into a file:
This method will overwrite the file if the file already exists. If you want to write
into an existing file, then you should use another method available.
Parameters
Here is the description of the parameters used:
path - This is the string having the file name including path.
61
Node.js
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.
Example
Let us create a js file named main.js having the following code:
var fs = require("fs");
$ node main.js
62
Node.js
Reading a File
Syntax
Following is the syntax of one of the methods to read from a file:
This method will use file descriptor to read the file. If you want to read the file
directly using the file name, then you should use another method available.
Parameters
Here is the description of the parameters used:
buffer - This is the buffer that the data will be written to.
callback - This is the callback function which gets the three arguments,
(err, bytesRead, buffer).
Example
Let us create a js file named main.js with the following code:
var fs = require("fs");
var buf = new Buffer(1024);
63
Node.js
if (err){
console.log(err);
}
console.log(bytes + " bytes read");
$ node main.js
Closing a File
Syntax
Following is the syntax to close an opened file:
fs.close(fd, callback)
Parameters
Here is the description of the parameters used:
64
Node.js
Example
Let us create a js file named main.js having the following code:
var fs = require("fs");
var buf = new Buffer(1024);
$ node main.js
65
Node.js
Truncate a File
Syntax
Following is the syntax of the method to truncate an opened file:
Parameters
Here is the description of the parameters used:
len - This is the length of the file after which the file will be truncated.
Example
Let us create a js file named main.js having the following code:
var fs = require("fs");
var buf = new Buffer(1024);
66
Node.js
$ node main.js
67
Node.js
Delete a File
Syntax
Following is the syntax of the method to delete a file:
fs.unlink(path, callback)
Parameters
Here is the description of the parameters used:
Example
Let us create a js file named main.js having the following code:
var fs = require("fs");
68
Node.js
$ node main.js
Create a Directory
Syntax
Following is the syntax of the method to create a directory:
Parameters
Here is the description of the parameters used:
Example
Let us create a js file named main.js having the following code:
var fs = require("fs");
$ node main.js
69
Node.js
Read a Directory
Syntax
Following is the syntax of the method to read a directory:
fs.readdir(path, callback)
Parameters
Here is the description of the parameters used:
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 '..'.
Example
Let us create a js file named main.js having the following code:
var fs = require("fs");
$ node main.js
70
Node.js
Remove a Directory
Syntax
Following is the syntax of the method to remove a directory:
fs.rmdir(path, callback)
Parameters
Here is the description of the parameters used:
Example
Let us create a js file named main.js having the following code:
var fs = require("fs");
71
Node.js
return console.error(err);
}
files.forEach( function (file){
console.log( file );
});
});
});
$ node main.js
Methods Reference
Following is a reference of File System module available in Node.js. For more
detail, you can refer to the official documentation.
fs.ftruncateSync(fd, len)
3
Synchronous ftruncate().
72
Node.js
fs.truncateSync(path, len)
5
Synchronous truncate().
fs.chmodSync(path, mode)
13
Synchronous chmod().
73
Node.js
fs.fchmodSync(fd, mode)
15
Synchronous fchmod().
fs.lchmodSync(path, mode)
17
Synchronous lchmod().
fs.stat(path, callback)
18 Asynchronous stat(). The callback gets two arguments (err, stats)
where stats is an fs.Stats object.
fs.lstat(path, callback)
Asynchronous lstat(). The callback gets two arguments (err, stats)
19 where stats is an fs.Stats object. lstat() is identical to stat(), except
that if path is a symbolic link, then the link itself is stat-ed, not the file
that it refers to.
fs.fstat(fd, callback)
Asynchronous fstat(). The callback gets two arguments (err, stats)
20
where stats is an fs.Stats object. fstat() is identical to stat(), except
that the file to be stat-ed is specified by the file descriptor fd.
fs.statSync(path)
21
Synchronous stat(). Returns an instance of fs.Stats.
fs.lstatSync(path)
22
Synchronous lstat(). Returns an instance of fs.Stats.
fs.fstatSync(fd)
23
Synchronous fstat(). Returns an instance of fs.Stats.
74
Node.js
fs.linkSync(srcpath, dstpath)
25
Synchronous link().
fs.readlink(path, callback)
28 Asynchronous readlink(). The callback gets two arguments (err,
linkString).
fs.realpathSync(path[, cache])
30
Synchronous realpath(). Returns the resolved path.
fs.unlink(path, callback)
31 Asynchronous unlink(). No arguments other than a possible exception
are given to the completion callback.
fs.unlinkSync(path)
32
Synchronous unlink().
fs.rmdir(path, callback)
33 Asynchronous rmdir(). No arguments other than a possible exception
are given to the completion callback.
75
Node.js
fs.rmdirSync(path)
34
Synchronous rmdir().
fs.mkdirSync(path[, mode])
36
Synchronous mkdir().
fs.readdir(path, callback)
Asynchronous readdir(3). Reads the contents of a directory. The
37
callback gets two arguments (err, files) where files is an array of the
names of the files in the directory excluding '.' and '..'.
fs.readdirSync(path)
38 Synchronous readdir(). Returns an array of filenames excluding '.' and
'..'.
fs.close(fd, callback)
39 Asynchronous close(). No arguments other than a possible exception
are given to the completion callback.
fs.closeSync(fd)
40
Synchronous close().
76
Node.js
fs.fsync(fd, callback)
47 Asynchronous fsync. No arguments other than a possible exception are
given to the completion callback.
fs.fsyncSync(fd)
48
Synchronous fsync.
77
Node.js
fs.readFileSync(filename[, options])
56 Synchronous version of fs.readFile. Returns the contents of the
filename.
fs.unwatchFile(filename[, listener])
Stop watching for changes on filename. If listener is specified, only that
62
particular listener is removed. Otherwise, all listeners are removed and
you have effectively stopped watching filename.
fs.exists(path, callback)
64 Test whether or not the given path exists by checking with the file
system. Then call the callback argument with either true or false.
fs.existsSync(path)
65
Synchronous version of fs.exists.
78
Node.js
fs.accessSync(path[, mode])
67 Synchronous version of fs.access. It throws if any accessibility checks
fail, and does nothing otherwise.
fs.createReadStream(path[, options])
68
Returns a new ReadStream object.
fs.createWriteStream(path[, options])
69
Returns a new WriteStream object.
79
Node.js
12. GLOBAL OBJECTS
Node.js global objects are global in nature and they are available in all modules.
We do not need to include these objects in our application, rather we can use them
directly. These objects are modules, functions, strings and object itself as
explained below.
__filename
The __filename represents the filename of the code being executed. This is the
resolved absolute path of this code file. For a main program, this is not necessarily
the same filename used in the command line. The value inside a module is the
path to that module file.
Example
Create a js file named main.js with the following code:
console.log( __filename );
$ node main.js
Based on the location of your program, it will print the main file name as follows:
/web/com/1427091028_21099/main.js
__dirname
The __dirname represents the name of the directory that the currently executing
script resides in.
Example
Create a js file named main.js with the following code:
console.log( __dirname );
80
Node.js
$ node main.js
Based on the location of your program, it will print the current directory name as
follows:
/web/com/1427091028_21099
setTimeout(cb, ms)
The setTimeout(cb, ms) global function is used to run callback cb after at least
ms milliseconds. The actual delay depends on external factors like OS timer
granularity and system load. A timer cannot span more than 24.8 days.
This function returns an opaque value that represents the timer which can be used
to clear the timer.
Example
Create a js file named main.js with the following code:
function printHello(){
console.log( "Hello, World!");
}
// Now call above function after 2 seconds
setTimeout(printHello, 2000);
$ node main.js
Hello, World!
clearTimeout (t)
The clearTimeout(t) global function is used to stop a timer that was previously
created with setTimeout(). Here t is the timer returned by the setTimeout()
function.
81
Node.js
Example
Create a js file named main.js with the following code:
function printHello(){
console.log( "Hello, World!");
}
// Now call above function after 2 seconds
var t = setTimeout(printHello, 2000);
$ node main.js
Verify the output where you will not find anything printed.
setInterval(cb, ms)
The setInterval(cb, ms) global function is used to run callback cb repeatedly
after at least ms milliseconds. The actual delay depends on external factors like
OS timer granularity and system load. A timer cannot span more than 24.8 days.
This function returns an opaque value that represents the timer which can be used
to clear the timer using the function clearInterval(t).
Example
Create a js file named main.js with the following code:
function printHello(){
console.log( "Hello, World!");
}
// Now call above function after 2 seconds
setInterval(printHello, 2000);
$ node main.js
The above program will execute printHello() after every 2 second. Due to system
limitation, this program cannot be executed with Try it option so you can check it
in your machine locally.
82
Node.js
Global Objects
The following table provides a list of other objects which we use frequently in our
applications. For more detail, you can refer to the official documentation.
Console
1
Used to print information on stdout and stderr.
Process
2 Used to get information on current process. Provides multiple events
related to process activities.
Console Object
Node.js console is a global object and is used to print different levels of messages
to stdout and stderr. There are built-in methods to be used for printing
informational, warning, and error messages.
Console Methods
Following is a list of methods available with the console global object.
console.log([data][, ...])
1 Prints to stdout with newline. This function can take multiple
arguments in a printf()-like way.
console.info([data][, ...])
2 Prints to stdout with newline. This function can take multiple
arguments in a printf()-like way.
console.error([data][, ...])
3 Prints to stderr with newline. This function can take multiple
arguments in a printf()-like way.
83
Node.js
console.warn([data][, ...])
4 Prints to stderr with newline. This function can take multiple
arguments in a printf()-like way
console.dir(obj[, options])
5
Uses util.inspect on obj and prints resulting string to stdout.
console.time(label)
6
Mark a time.
console.timeEnd(label)
7
Finish timer, record output.
console.trace(message[, ...])
8 Print to stderr 'Trace :', followed by the formatted message and stack
trace to the current position.
Example
Let us create a js file named main.js with the following code:
console.info("Program Started");
console.time("Getting data");
//
// Do some processing here...
//
console.timeEnd('Getting data');
console.info("Program Ended")
84
Node.js
node main.js
Program Started
Counter: 10
Getting data: 0ms
Program Ended
Process Object
The process object is a global object and can be accessed from anywhere. There
are several methods available in a process object.
Process Events
The process object is an instance of EventEmitter and emits the following events:
exit
Emitted when the process is about to exit. There is no way to prevent the
1
exiting of the event loop at this point, and once all exit listeners have
finished running, the process will exit.
beforeExit
This event is emitted when node empties its event loop and has nothing
2 else to schedule. Normally, the node exits when there is no work
scheduled, but a listener for 'beforeExit' can make asynchronous calls,
and cause the node to continue.
uncaughtException
Emitted when an exception bubbles all the way back to the event loop. If
3
a listener is added for this exception, the default action (which is to print
a stack trace and exit) will not occur.
Signal Events
4 Emitted when the processes receives a signal such as SIGINT, SIGHUP,
etc.
85
Node.js
Example
Create a js file named main.js with the following code for listening for exit event:
process.on('exit', function(code) {
$ node main.js
Program Ended
About to exit with code: 0
Exit Codes
Node normally exits with a 0 status code when no more async operations are
pending. There are other exit codes which are described below:
Unused
2
reserved by Bash for built-in misuse.
86
Node.js
caused a parse error. This is extremely rare, and generally can only
happen during the development of Node itself.
Fatal Error
5 There was a fatal unrecoverable error in V8. Typically, a message will
be printed to stderr with the prefix FATAL ERROR.
8 Unused
Invalid Argument
9 Either an unknown option was specified, or an option requiring a
value was provided without a value.
87
Node.js
Signal Exits
If Node receives a fatal signal such as SIGKILL or SIGHUP, then its
exit code will be 128 plus the value of the signal code. This is a
>128
standard Unix practice, since exit codes are defined to be 7-bit
integers, and signal exits set the high-order bit, and then contain the
value of the signal code.
Process Properties
Process provides many useful properties to get better control over system
interactions.
stdout
1
A Writable Stream to stdout.
stderr
2
A Writable Stream to stderr.
stdin
3
A Writable Stream to stdin.
argv
An array containing the command-line arguments. The first element
4 will be 'node', the second element will be the name of the JavaScript
file. The next elements will be any additional command-line
arguments.
execPath
5 This is the absolute pathname of the executable that started the
process.
execArgv
6 This is the set of node-specific command line options from the
executable that started the process.
env
7
An object containing the user environment.
88
Node.js
exitCode
A number which will be the process exit code, when the process either
8
exits gracefully, or is exited via process.exit() without specifying a
code.
version
9
A compiled-in property that exposes NODE_VERSION.
versions
10
A property exposing the version strings of node and its dependencies.
config
An Object containing the JavaScript representation of the configure
11 options that were used to compile the current node executable. This is
the same as the "config.gypi" file that was produced when running the
./configure script.
pid
12
The PID of the process.
title
13
Getter/setter to set what is displayed in 'ps'.
arch
14
What processor architecture you're running on: 'arm', 'ia32', or 'x64'.
platform
15 What platform you're running on: 'darwin', 'freebsd', 'linux', 'sunos' or
'win32'
mainModule
Alternate way to retrieve require.main. The difference is that if the
main module changes at runtime, require.main might still refer to the
16
original main module in modules that were required before the change
occurred. Generally it's safe to assume that the two refer to the same
module.
89
Node.js
Example
Create a js file named main.js with the following code:
// Printing to console
process.stdout.write("Hello World!" + "\n");
// Platform Information
console.log(process.platform);
$ node main.js
Hello World!
0: node
1: /web/com/1427106219_25089/main.js
/usr/bin/node
linux
90
Node.js
Methods Reference
Process provides many useful methods to get better control over system
interactions.
abort()
1 It causes the node to emit an abort. It causes the node to exit and
generate a core file.
chdir(directory)
2 Changes the current working directory of the process or throws an
exception if that fails.
cwd()
3
Returns the current working directory of the process.
exit([code])
4 Ends the process with the specified code. If omitted, exit uses the
'success' code 0.
getgid()
Gets the group identity of the process. This is the numerical group id,
5
not the group name. This function is available only on POSIX platforms
(i.e. not Windows, Android).
setgid(id)
Sets the group identity of the process (See setgid(2)). It accepts either
6 a numerical ID or a groupname string. If a groupname is specified, this
method blocks while resolving it to a numerical ID. This function is
available only on POSIX platforms (i.e. not Windows, Android).
getuid()
Gets the user identity of the process. This is the numerical id, not the
7
username. This function is only available on POSIX platforms (i.e. not
Windows, Android).
8 setuid(id)
Sets the user identity of the process (See setgid(2)). It accepts either a
91
Node.js
getgroups()
Returns an array with the supplementary group IDs. POSIX leaves it
9 unspecified if the effective group ID is included, but node.js ensures it
always is. This function is available only on POSIX platforms (i.e. not
Windows, Android).
setgroups(groups)
Sets the supplementary group IDs. This is a privileged operation, which
10 implies that you have to be at the root or have the CAP_SETGID
capability. This function is available only on POSIX platforms (i.e. not
Windows, Android).
initgroups(user, extra_group)
Reads /etc/group and initializes the group access list, using all the
groups of which the user is a member. This is a privileged operation,
11
which implies that you have to be at the root or have the CAP_SETGID
capability. This function is available only on POSIX platforms (i.e. not
Windows, Android).
kill(pid[, signal])
Send a signal to a process. pid is the process id and signal is the string
12
describing the signal to send. Signal names are strings like 'SIGINT' or
'SIGHUP'. If omitted, the signal will be 'SIGTERM'.
memoryUsage()
13 Returns an object describing the memory usage of the Node process
measured in bytes.
nextTick(callback)
14 Once the current event loop turn runs to completion, call the callback
function.
15 umask([mask])
Sets or reads the process's file mode creation mask. Child processes
92
Node.js
inherit the mask from the parent process. Returns the old mask if mask
argument is given, otherwise returns the current mask.
uptime()
16
Number of seconds Node has been running.
hrtime()
Returns the current high-resolution real time in a [seconds,
17 nanoseconds] tuple Array. It is relative to an arbitrary time in the past.
It is not related to the time of day and therefore not subject to clock
drift. The primary use is for measuring performance between intervals.
Example
Create a js file named main.js with the following code:
$ node main.js
93
Node.js
13. UTILITY MODULES
There are several utility modules available in Node.js module library. These
modules are very common and are frequently used while developing any Node-
based application.
OS Module
1
Provides basic operating-system related utility functions.
Path Module
2
Provides utilities for handling and transforming file paths.
Net Module
3 Provides both servers and clients as streams. Acts as a network
wrapper.
DNS Module
4 Provides functions to do actual DNS lookup as well as to use
underlying operating system name resolution functionalities.
Domain Module
5 Provides ways to handle multiple different I/O operations as a single
group.
OS Module
Node.js os module provides a few basic operating-system related utility functions.
This module can be imported using the following syntax.
var os = require("os")
94
Node.js
Methods
os.tmpdir()
1
Returns the operating system's default directory for temp files.
os.endianness()
2
Returns the endianness of the CPU. Possible values are "BE" or "LE".
os.hostname()
3
Returns the hostname of the operating system.
os.type()
4
Returns the operating system name.
os.platform()
5
Returns the operating system platform.
os.arch()
6 Returns the operating system CPU architecture. Possible values are "x64",
"arm" and "ia32".
os.release()
7
Returns the operating system release.
os.uptime()
8
Returns the system uptime in seconds.
os.loadavg()
9
Returns an array containing the 1, 5, and 15 minute load averages.
os.totalmem()
10
Returns the total amount of system memory in bytes.
os.freemem()
11
Returns the amount of free system memory in bytes.
95
Node.js
os.cpus()
Returns an array of objects containing information about each CPU/core
12 installed: model, speed (in MHz), and times (an object containing the
number of milliseconds the CPU/core spent in: user, nice, sys, idle, and
irq).
os.networkInterfaces()
13
Get a list of network interfaces.
Properties
os.EOL
1 A constant defining the appropriate End-of-line marker for the
operating system.
Example
The following example demonstrates a few OS methods. Create a js file named
main.js with the following code.
var os = require("os");
// Endianness
console.log('endianness : ' + os.endianness());
// OS type
console.log('type : ' + os.type());
// OS platform
console.log('platform : ' + os.platform());
96
Node.js
$ node main.js
endianness : LE
type : Linux
platform : linux
total memory : 25103400960 bytes.
free memory : 20676710400 bytes.
Path Module
Node.js path module is used for handling and transforming file paths. This module
can be imported using the following syntax.
Methods
path.normalize(p)
1
Normalize a string path, taking care of '..' and '.' parts.
path.isAbsolute(path)
Determines whether the path is an absolute path. An absolute path
4
will always resolve to the same location, regardless of the working
directory.
97
Node.js
path.relative(from, to)
5
Solve the relative path from from to to.
path.dirname(p)
6 Return the directory name of a path. Similar to the Unix dirname
command.
path.basename(p[, ext])
7 Return the last portion of a path. Similar to the Unix basename
command.
path.extname(p)
Return the extension of the path, from the last '.' to end of string in
8
the last portion of the path. If there is no '.' in the last portion of the
path or the first character of it is '.', then it returns an empty string.
path.parse(pathString)
9
Returns an object from a path string.
path.format(pathObject)
10 Returns a path string from an object, the opposite of path.parse
above.
Properties
path.sep
1
The platform-specific file separator. '\\' or '/'.
path.delimiter
2
The platform-specific path delimiter, ; or ':'.
path.posix
3 Provide access to aforementioned path methods but always interact in
a posix compatible way.
98
Node.js
path.win32
4 Provide access to aforementioned path methods but always interact in
a win32 compatible way.
Example
Create a js file named main.js with the following code:
// Normalization
console.log('normalization : ' +
path.normalize('/test/test1//2slashes/1slash/tab/..'));
// Join
console.log('joint path : ' + path.join('/test', 'test1',
'2slashes/1slash', 'tab', '..'));
// Resolve
console.log('resolve : ' + path.resolve('main.js'));
// extName
console.log('ext name : ' + path.extname('main.js'));
$ node main.js
normalization : /test/test1/2slashes/1slash
joint path : /test/test1/2slashes/1slash
resolve : /web/com/1427176256_27423/main.js
ext name : .js
Net Module
Node.js net module is used to create both servers and clients. This module
provides an asynchronous network wrapper and it can be imported using the
following syntax.
99
Node.js
Methods
net.createServer([options][, connectionListener])
1 Creates a new TCP server. The connectionListener argument is
automatically set as a listener for the 'connection' event.
net.connect(options[, connectionListener])
2 A factory method, which returns a new 'net.Socket' and connects to the
supplied address and port.
net.createConnection(options[, connectionListener])
3 A factory method, which returns a new 'net.Socket' and connects to the
supplied address and port.
net.connect(path[, connectListener])
Creates Unix socket connection to path. The connectListener parameter
6
will be added as a listener for the 'connect' event. It is a factory method
which returns a new 'net.Socket'.
net.createConnection(path[, connectListener])
Creates Unix socket connection to path. The connectListener parameter
7
will be added as a listener for the 'connect' event. It is a factory method
which returns a new 'net.Socket'.
100
Node.js
net.isIP(input)
8 Tests if the input is an IP address. Returns 0 for invalid strings, 4 for IP
version 4 addresses, and 6 for IP version 6 addresses.
net.isIPv4(input)
9 Returns true if the input is a version 4 IP address, otherwise returns
false.
net.isIPv6(input)
10 Returns true if the input is a version 6 IP address, otherwise returns
false.
Class net.Server
This class is used to create a TCP or local server.
Methods
server.listen(path[, callback])
2
Start a local socket server listening for connections on the given path.
server.listen(handle[, callback])
The handle object can be set to either a server or socket (anything with
an underlying _handle member), or a {fd: <n>} object. It will cause the
3 server to accept connections on the specified handle, but it is presumed
that the file descriptor or handle has already been bound to a port or
domain socket. Listening on a file descriptor is not supported on
Windows.
server.listen(options[, callback])
4 The port, host, and backlog properties of options, as well as the optional
callback function, behave as they do on a call to server.listen(port,
101
Node.js
server.close([callback])
5 Finally closed when all connections are ended and the server emits a
'close' event.
server.address()
6 Returns the bound address, the address family name and port of the
server as reported by the operating system.
server.unref()
Calling unref on a server will allow the program to exit if this is the only
7
active server in the event system. If the server is already unrefd, then
calling unref again will have no effect.
server.ref()
Opposite of unref, calling ref on a previously unrefd server will not let
8
the program exit if it's the only server left (the default behavior). If the
server is refd, then calling the ref again will have no effect.
server.getConnections(callback)
Asynchronously get the number of concurrent connections on the server.
9
Works when sockets were sent to forks. Callback should take two
arguments err and count.
Events
listening
1
Emitted when the server has been bound after calling server.listen.
connection
Emitted when a new connection is made. Socket object, the connection
2
object is available to event handler. Socket is an instance of
net.Socket.
102
Node.js
close
3 Emitted when the server closes. Note that if connections exist, this
event is not emitted until all the connections are ended.
error
4 Emitted when an error occurs. The 'close' event will be called directly
following this event.
Class net.Socket
This object is an abstraction of a TCP or local socket. net.Socket instances
implement a duplex Stream interface. They can be created by the user and used
as a client (with connect()) or they can be created by Node and passed to the user
through the 'connection' event of a server.
Events
net.Socket is an eventEmitter and it emits the following events.
lookup
1 Emitted after resolving the hostname but before connecting. Not
applicable to UNIX sockets.
connect
2
Emitted when a socket connection is successfully established.
data
3 Emitted when data is received. The argument data will be a Buffer or
String. Encoding of data is set by socket.setEncoding().
end
4
Emitted when the other end of the socket sends a FIN packet.
timeout
Emitted if the socket times out from inactivity. This is only to notify
5
that the socket has been idle. The user must manually close the
connection.
103
Node.js
drain
6 Emitted when the write buffer becomes empty. Can be used to throttle
uploads.
error
7 Emitted when an error occurs. The 'close' event will be called directly
following this event.
close
Emitted once the socket is fully closed. The argument had_error is a
8
boolean which indicates if the socket was closed due to a transmission
error.
Properties
net.Socket provides many useful properties to get better control over socket
interactions.
socket.bufferSize
1 This property shows the number of characters currently buffered to be
written.
socket.remoteAddress
2 The string representation of the remote IP address. For example,
'74.125.127.100' or '2001:4860:a005::68'.
socket.remoteFamily
3
The string representation of the remote IP family. 'IPv4' or 'IPv6'.
socket.remotePort
4
The numeric representation of the remote port. For example, 80 or 21.
socket.localAddress
The string representation of the local IP address the remote client is
5
connecting on. For example, if you are listening on '0.0.0.0' and the
client connects on '192.168.1.1', the value would be '192.168.1.1'.
104
Node.js
socket.localPort
6
The numeric representation of the local port. For example, 80 or 21.
socket.bytesRead
7
The amount of received bytes.
socket.bytesWritten
8
The amount of bytes sent.
Methods
new net.Socket([options])
1
Construct a new socket object.
socket.connect(path[, connectListener])
Opens the connection for a given socket. If port and host are given,
3 then the socket will be opened as a TCP socket, if host is omitted,
localhost will be assumed. If a path is given, the socket will be
opened as a Unix socket to that path.
socket.setEncoding([encoding])
4
Set the encoding for the socket as a Readable Stream.
socket.end([data][, encoding])
6 Half-closes the socket, i.e., it sends a FIN packet. It is possible the
server will still send some data.
105
Node.js
socket.destroy()
7 Ensures that no more I/O activity happens on this socket. Necessary
only in case of errors (parse error or so).
socket.pause()
8 Pauses the reading of data. That is, 'data' events will not be emitted.
Useful to throttle back an upload.
socket.resume()
9
Resumes reading after a call to pause().
socket.setTimeout(timeout[, callback])
10 Sets the socket to timeout after timeout milliseconds of inactivity on
the socket. By default, net.Socket does not have a timeout.
socket.setNoDelay([noDelay])
Disables the Nagle algorithm. By default, TCP connections use the
11 Nagle algorithm, they buffer data before sending it off. Setting true
for noDelay will immediately fire off data each time socket.write() is
called. noDelay defaults to true.
socket.setKeepAlive([enable][, initialDelay])
Enable/disable keep-alive functionality, and optionally set the initial
12
delay before the first keepalive probe is sent on an idle socket.
enable defaults to false.
socket.address()
Returns the bound address, the address family name, and the port
13 of the socket as reported by the operating system. Returns an
object with three properties, e.g. { port: 12346, family: 'IPv4',
address: '127.0.0.1' }.
socket.unref()
Calling unref on a socket will allow the program to exit if this is the
14
only active socket in the event system. If the socket is already
unrefd, then calling unref again will have no effect.
15 socket.ref()
Opposite of unref, calling ref on a previously unrefd socket will not
106
Node.js
let the program exit if it's the only socket left (the default behavior).
If the socket is refd, then calling ref again will have no effect.
Example
Create a js file named server.js with the following code:
File: server.js
var net = require('net');
var server = net.createServer(function(connection) {
console.log('client connected');
connection.on('end', function() {
console.log('client disconnected');
});
connection.write('Hello World!\r\n');
connection.pipe(connection);
});
server.listen(8080, function() {
console.log('server is listening');
});
$ node server.js
server is listening
File: client.js
var net = require('net');
var client = net.connect({port: 8080}, function() {
console.log('connected to server!');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
107
Node.js
});
client.on('end', function() {
console.log('disconnected from server');
});
Now run the client.js from another terminal to see the result:
$ node client.js
connected to server!
Hello World!
server is listening
client connected
client disconnected
DNS Module
Node.js dns module is used to do actual DNS lookup as well as to use underlying
operating system name resolution functionalities. This module provides an
asynchronous network wrapper and can be imported using the following syntax.
Methods
108
Node.js
dns.resolve4(hostname, callback)
The same as dns.resolve(), but only for IPv4 queries (A records).
4
addresses is an array of IPv4 addresses (e.g. ['74.125.79.104',
'74.125.79.105', '74.125.79.106']).
dns.resolve6(hostname, callback)
5
The same as dns.resolve4() except for IPv6 queries (an AAAA query).
dns.resolveMx(hostname, callback)
6 The same as dns.resolve(), but only for mail exchange queries (MX
records).
dns.resolveTxt(hostname, callback)
The same as dns.resolve(), but only for text queries (TXT records).
addresses is an 2-d array of the text records available for hostname
7
(e.g., [ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]). Each sub-array contains TXT
chunks of one record. Depending on the use case, they could be either
joined together or treated separately.
dns.resolveSrv(hostname, callback)
The same as dns.resolve(), but only for service records (SRV records).
addresses is an array of the SRV records available for hostname.
8
Properties of SRV records are priority, weight, port, and name (e.g.,
[{'priority': 10, 'weight': 5, 'port': 21223, 'name':
'service.example.com'}, ...]).
dns.resolveSoa(hostname, callback)
9 The same as dns.resolve(), but only for start of authority record queries
(SOA record).
109
Node.js
dns.resolveNs(hostname, callback)
The same as dns.resolve(), but only for name server records (NS
10
records). addresses is an array of the name server records available for
hostname (e.g., ['ns1.example.com', 'ns2.example.com']).
dns.resolveCname(hostname, callback)
The same as dns.resolve(), but only for canonical name records (CNAME
11
records). addresses is an array of the canonical name records available
for hostname (e.g., ['bar.example.com']).
dns.reverse(ip, callback)
12
Reverse resolves an ip address to an array of hostnames.
dns.getServers()
13 Returns an array of IP addresses as strings that are currently being used
for resolution.
dns.setServers(servers)
14 Given an array of IP addresses as strings, set them as the servers to use
for resolving.
rrtypes
Following is the list of valid rrtypes used by dns.resolve() method:
Error Codes
Each DNS query can return one of the following error codes:
110
Node.js
Example
Create a js file named main.js with the following code:
111
Node.js
$ node main.js
address: 173.194.46.83
reverse for 173.194.46.83: ["ord08s11-in-f19.1e100.net"]
Domain Module
Node.js domain module is used to intercept unhandled error. These unhandled
error can be intercepted using internal binding or external binding. If errors are
not handled at all, then they will simply crash the Node application.
Internal Binding - Error emitter is executing its code within the run
method of a domain.
112
Node.js
Methods
domain.run(function)
Run the supplied function in the context of the domain, implicitly
1
binding all event emitters, timers, and low-level requests that are
created in that context. This is the most basic way to use a domain.
domain.add(emitter)
Explicitly adds an emitter to the domain. If any event handlers called
2
by the emitter throw an error, or if the emitter emits an error event, it
will be routed to the domain's error event, just like with implicit binding.
domain.remove(emitter)
3 The opposite of domain.add(emitter). Removes domain handling from
the specified emitter.
domain.bind(callback)
The returned function will be a wrapper around the supplied callback
4
function. When the returned function is called, any errors that are
thrown will be routed to the domain's error event.
domain.intercept(callback)
This method is almost identical to domain.bind(callback). However, in
5
addition to catching thrown errors, it will also intercept Error objects
sent as the first argument to the function.
domain.enter()
The enter method is plumbing used by the run, bind, and intercept
methods to set the active domain. It sets domain.active and
6 process.domain to the domain, and implicitly pushes the domain onto
the domain stack managed by the domain module (see domain.exit()
for details on the domain stack). The call to enter delimits the beginning
of a chain of asynchronous calls and I/O operations bound to a domain.
domain.exit()
7 The exit method exits the current domain, popping it off the domain
stack. Whenever the execution switches to the context of a different
chain of asynchronous calls, it's important to ensure that the current
113
Node.js
domain.dispose()
Once dispose has been called, the domain will no longer be used by
8
callbacks bound into the domain via run, bind, or intercept, and a
dispose event is emit
Properties
domain.members
1 An array of timers and event emitters that have been explicitly added
to the domain.
Example
Create a js file named main.js with the following code:
// Create a domain
var domain1 = domain.create();
domain1.on('error', function(err){
console.log("domain1 handled this error ("+err.message+")");
});
// Explicit binding
domain1.add(emitter1);
emitter1.on('error',function(err){
114
Node.js
emitter1.removeAllListeners('error');
domain2.on('error', function(err){
console.log("domain2 handled this error ("+err.message+")");
});
// Implicit binding
domain2.run(function(){
var emitter2 = new EventEmitter();
emitter2.emit('error',new Error('To be handled by domain2'));
});
domain1.remove(emitter1);
emitter1.emit('error', new Error('Converted to exception. System will
crash!'));
$ node main.js
events.js:72
115
Node.js
116
Node.js
14. WEB MODULE
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.
Server - This layer has the Web server which can intercept the requests
made by the clients and pass them the response.
117
Node.js
Data - This layer contains the databases or any other source of data.
File: server.js
var http = require('http');
var fs = require('fs');
var url = require('url');
// Create a server
http.createServer( function (request, response) {
// Parse the request containing file name
var pathname = url.parse(request.url).pathname;
118
Node.js
Next let's create the following html file named index.htm in the same directory
where you created server.js
File: index.htm
<html>
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
</body>
</html>
$ node server.js
119
Node.js
File: client.js
var http = require('http');
120
Node.js
response.on('end', function() {
// Data received completely.
console.log(body);
});
}
// Make a request to the server
var req = http.request(options, callback);
req.end();
Now run the client.js from a different command terminal other than server.js to
see the result:
$ node client.js
<html>
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
</body>
</html>
121
Node.js
15. EXPRESS FRAMEWORK
Express Overview
Express is a minimal and flexible Node.js web application framework that provides
a robust set of features to develop web and mobile applications. It facilitates the
rapid development of Node-based Web applications. Following are some of the
core features of Express framework:
Installing Express
Firstly, install the Express framework globally using NPM so that it can be used to
create a web application using node terminal.
The above command saves the installation locally in the node_modules directory
and creates a directory express inside node_modules. You should install the
following important modules along with express:
122
Node.js
})
Save the above code in a file named server.js and run it with the following
command.
$ node server.js
123
Node.js
Request Object - The request object represents the HTTP request and has
properties for the request query string, parameters, body, HTTP headers,
and so on.
Response Object - The response object represents the HTTP response that
an Express app sends when it gets an HTTP request.
You can print req and res objects which provide a lot of information related to
HTTP request and response including cookies, sessions, URL, etc.
Request Object
The req object represents the HTTP request and has properties for the request
query string, parameters, body, HTTP headers, and so on.
124
Node.js
req.app
1 This property holds a reference to the instance of the express
application that is using the middleware.
req.baseUrl
2
The URL path on which a router instance was mounted.
req.body
Contains key-value pairs of data submitted in the request body. By
3
default, it is undefined, and is populated when you use body-parsing
middleware such as body-parser
req.cookies
4 When using cookie-parser middleware, this property is an object that
contains cookies sent by the request.
req.fresh
5
Indicates whether the request is "fresh." It is the opposite of req.stale.
req.hostname
6
Contains the hostname from the "Host" HTTP header.
req.ip
7
The remote IP address of the request.
req.ips
8 When the trust proxy setting is true, this property contains an array of
IP addresses specified in the X-Forwarded-For request header.
req.originalUrl
This property is much like req.url; however, it retains the original
9
request URL, allowing you to rewrite req.url freely for internal routing
purposes.
125
Node.js
req.params
An object containing properties mapped to the named route
10 parameters. For example, if you have the route /user/:name, then
the "name" property is available as req.params.name. This object
defaults to {}.
req.path
11
Contains the path part of the request URL.
req.protocol
12
The request protocol string, "http" or "https" when requested with TLS.
req.query
13 An object containing a property for each query string parameter in the
route.
req.route
14
The currently-matched route, a string.
req.secure
15
A Boolean that is true if a TLS connection is established.
req.signedCookies
16 When using cookie-parser middleware, this property contains signed
cookies sent by the request, unsigned and ready for use.
req.stale
17 Indicates whether the request is "stale," and is the opposite of
req.fresh.
req.subdomains
18
An array of subdomains in the domain name of the request.
req.xhr
A Boolean value that is true if the requests "X-Requested-With" header
19
field is XMLHttpRequest, indicating that the request was issued by a
client library such as jQuery
126
Node.js
This method checks if the specified content types are acceptable, based on the
requests Accept HTTP header field. Following are a few examples:
// Accept: text/html
req.accepts('html');
// => "html"
req.get(field)
req.get(field)
This method returns the specified HTTP request header field. Following are a few
examples:
req.get('Content-Type');
// => "text/plain"
req.get('content-type');
// => "text/plain"
req.get('Something');
// => undefined
req.is(type)
req.is(type)
This method returns true if the incoming requests "Content-Type" HTTP header
field matches the MIME type specified by the type parameter. Following are a few
examples:
127
Node.js
req.param(name [, defaultValue])
req.param(name [, defaultValue])
This method returns the value of param name when present. Following are few
examples:
// ?name=tobi
req.param('name')
// => "tobi"
// POST name=tobi
req.param('name')
// => "tobi"
Response Object
The res object represents the HTTP response that an Express app sends when it
gets an HTTP request.
res.app
1 This property holds a reference to the instance of the express application
that is using the middleware.
128
Node.js
res.headersSent
2 Boolean property that indicates if the app sent HTTP headers for the
response.
res.locals
3
An object that contains response local variables scoped to the request.
This method appends the specified value to the HTTP response header field.
Following are a few examples:
res.attachment([filename])
res.attachment([filename])
res.attachment('path/to/logo.png');
This method is used to set cookie name to value. The value parameter may be a
string or object converted to JSON. Following are a few examples:
129
Node.js
res.clearCookie(name [, options])
res.clearCookie(name [, options])
This method is used to clear the cookie specified by name. Following are a few
examples:
res.download('/report-12345.pdf');
res.download('/report-12345.pdf', 'report.pdf');
});
res.end([data] [, encoding])
res.end([data] [, encoding])
This method is used to end the response process. Following are a few examples:
res.end();
res.status(404).end();
res.format(object)
res.format(object)
res.format({
'text/plain': function(){
130
Node.js
res.send('hey');
},
'text/html': function(){
res.send('
hey
');
},
'application/json': function(){
res.send({ message: 'hey' });
},
'default': function() {
// log the request and respond with 406
res.status(406).send('Not Acceptable');
}
});
res.get(field)
res.get(field)
This method is used to return the HTTP response header specified by field. Here
is an example:
res.get('Content-Type');
res.json([body])
res.json([body])
This method is used to send a JSON response. Following are a few examples:
res.json(null)
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })
131
Node.js
res.jsonp([body])
res.jsonp([body])
This method is used to send a JSON response with JSONP support. Following are
a few examples:
res.jsonp(null)
res.jsonp({ user: 'tobi' })
res.status(500).jsonp({ error: 'message' })
res.links(links)
res.links(links)
This method is used to join the links provided as properties of the parameter to
populate the responses Link HTTP header field. Following are a few examples:
res.links({
next: 'http://api.example.com/users?page=2',
last: 'http://api.example.com/users?page=5'
});
res.location(path)
res.location(path)
This method is used to set the response Location HTTP header field based on the
specified path parameter. Following are a few examples:
res.location('/foo/bar');
res.location('foo/bar');
res.location('http://example.com');
res.redirect([status,] path)
res.redirect([status,] path)
This method is used to redirect to the URL dervied from the specified path, with
specified HTTP status code status. Following are a few examples:
res.redirect('/foo/bar');
res.redirect('http://example.com');
res.redirect(301, 'http://example.com');
132
Node.js
This method is used to render a view and sends the rendered HTML string to the
client. Following are a few examples:
res.send([body])
res.send([body])
This method is used to send the HTTP response. Following are a few examples:
res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('
some html
');
This method is used to transfer the file at the given path. Sets the Content-Type
response HTTP header field based on the filenames extension. Here is an
example:
res.sendStatus(statusCode)
res.sendStatus(statusCode)
133
Node.js
This method is used to set the response HTTP status code to statusCode and send
its string representation as the response body. Following are a few examples:
res.set(field [, value])
res.set(field [, value])
This method is used to set the responses HTTP header field to value. Following
are a few examples:
res.set('Content-Type', 'text/plain');
res.set({
'Content-Type': 'text/plain',
'Content-Length': '123',
'ETag': '12345'
})
res.status(code)
res.status(code)
This method is used to set the HTTP status for the response. Following are a few
examples:
res.status(403).end();
res.status(400).send('Bad Request');
res.status(404).sendFile('/absolute/path/to/404.png');
res.type(type)
res.type(type)
This method is used to set the Content-Type HTTP header to the MIME type.
Following are a few examples:
134
Node.js
Basic Routing
We have seen a basic application which serves HTTP request for the homepage.
Routing refers to determining how an application responds to a client request to a
particular endpoint, which is a URI (or path) and a specific HTTP request method
(GET, POST, and so on).
We will extend our Hello World program to handle more types of HTTP requests.
135
Node.js
})
Save the above code in a file named server.js and run it with the following
command.
$ node server.js
Now you can try different requests at http://127.0.0.1:8081 to see the output
generated by server.js. Following are a few screenshots showing different
responses for different URLs.
136
Node.js
137
Node.js
You simply need to pass the name of the directory where you keep your static
assets, to the express.static middleware to start serving the files directly. For
example, if you keep your images, CSS, and JavaScript files in a directory named
public, you can do this:
app.use(express.static('public'));
node_modules
server.js
public/
public/images
public/images/logo.png
Let's modify "Hello Word" app to add the functionality to handle static files.
app.use(express.static('public'));
138
Node.js
})
Save the above code in a file named server.js and run it with the following
command.
$ node server.js
GET Method
Here is a simple example which passes two values using HTML FORM GET method.
We are going to use process_get router inside server.js to handle this input.
139
Node.js
<html>
<body>
<form action="http://127.0.0.1:8081/process_get" method="GET">
First Name: <input type="text" name="first_name"> <br>
Let's save above code in index.htm and modify server.js to handle homepage
requests as well as the input sent by the HTML form.
app.use(express.static('public'));
140
Node.js
})
Now you can enter the First and Last Name and then click submit button to see
the result and it should return the following result:
{"first_name":"John","last_name":"Paul"}
POST Method
Here is a simple example which passes two values using HTML FORM POST
method. We are going to use process_get router inside server.js to handle this
input.
<html>
<body>
<form action="http://127.0.0.1:8081/process_post" method="POST">
First Name: <input type="text" name="first_name"> <br>
141
Node.js
Let's save the above code in index.htm and modify server.js to handle homepage
requests as well as the input sent by the HTML form.
app.use(express.static('public'));
})
142
Node.js
Now you can enter the First and Last Name and then click the submit button to
see the following result:
{"first_name":"John","last_name":"Paul"}
File Upload
The following HTML code creates a file uploader form. This form has method
attribute set to POST and enctype attribute is set to multipart/form-data
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="http://127.0.0.1:8081/file_upload" method="POST"
enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
143
Node.js
Let's save above code in index.htm and modify server.js to handle homepage
requests as well as file upload.
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}));
console.log(req.files.file.name);
console.log(req.files.file.path);
console.log(req.files.file.type);
144
Node.js
})
Cookies Management
You can send cookies to a Node.js server which can handle the same using the
following middleware option. Following is a simple example to print all the cookies
sent by the client.
145
Node.js
app.listen(8081)
146
Node.js
16. RESTFUL API
A REST Server simply provides access to resources and a 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,
for example, text, JSON, XML, but JSON is the most popular one.
HTTP methods
The following four HTTP methods are commonly used in REST based architecture.
Web services based on REST Architecture are known as RESTful web services.
These web services use HTTP methods to implement the concept of REST
architecture. A RESTful web service usually defines a URI, Uniform Resource
Identifier, which provides resource representation such as JSON and a set of HTTP
Methods.
147
Node.js
{
"user1" : {
"name" : "mahesh",
"password" : "password1",
"profession" : "teacher",
"id": 1
},
"user2" : {
"name" : "suresh",
"password" : "password2",
"profession" : "librarian",
"id": 2
},
"user3" : {
"name" : "ramesh",
"password" : "password3",
"profession" : "clerk",
"id": 3
}
}
Based on this information, we are going to provide the following RESTful APIs.
HTTP
S. No. URI POST body Result
Method
148
Node.js
We are keeping most of the part of all the examples in the form of hard-coding,
assuming you already know how to pass values from the front-end using Ajax or
simple form data and how to process them using express Request object.
List Users
Let's implement our first RESTful API listUsers using the following code in a
server.js file:
})
You can change the given IP address when you will put the solution in production
environment.
149
Node.js
{
"user1" : {
"name" : "mahesh",
"password" : "password1",
"profession" : "teacher",
"id": 1
},
"user2" : {
"name" : "suresh",
"password" : "password2",
"profession" : "librarian",
"id": 2
},
"user3" : {
"name" : "ramesh",
"password" : "password3",
"profession" : "clerk",
"id": 3
}
}
Add Users
Following API will show you how to add a new user in the list. Following is the
detail of the new user:
user = {
"user4" : {
"name" : "mohit",
"password" : "password4",
"profession" : "teacher",
"id": 4
}
}
150
Node.js
You can accept the same input in the form of JSON using Ajax call but for
demonstration purpose, we are hard-coding it here. Following is the addUser API
to a new user in the database:
var user = {
"user4" : {
"name" : "mohit",
"password" : "password4",
"profession" : "teacher",
"id": 4
}
}
})
151
Node.js
{ user1:
{ name: 'mahesh',
password: 'password1',
profession: 'teacher',
id: 1 },
user2:
{ name: 'suresh',
password: 'password2',
profession: 'librarian',
id: 2 },
user3:
{ name: 'ramesh',
password: 'password3',
profession: 'clerk',
id: 3 },
user4:
{ name: 'mohit',
password: 'password4',
profession: 'teacher',
id: 4 }
}
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.
152
Node.js
})
Now let's call the above service using http://127.0.0.1:8081/2 on your local
machine. It should produce following result:
{
"name":"suresh",
"password":"password2",
"profession":"librarian",
"id":2
}
Delete a 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 the user with ID 2.
var id = 2;
153
Node.js
console.log( data );
res.end( JSON.stringify(data));
});
})
})
{ user1:
{ name: 'mahesh',
password: 'password1',
profession: 'teacher',
id: 1 },
user3:
{ name: 'ramesh',
password: 'password3',
profession: 'clerk',
id: 3 }
}
154
Node.js
17. SCALING AN APPLICATION
Node provides child_process module which has the following three major ways
to create a child process.
Parameters
Here is the description of the parameters used:
155
Node.js
callback The function gets three arguments error, stdout, and stderr
which are called with the output when the process terminates.
The exec() method returns a buffer with a max size and waits for the process to
end and tries to return all the buffered data at once.
Example
Let us create two js files named support.js and master.js:
File: support.js
console.log("Child Process " + process.argv[2] + " executed." );
File: master.js
const fs = require('fs');
const child_process = require('child_process');
156
Node.js
$ node master.js
stderr:
Child process exited with exit code 0
stdout: Child Process 0 executed.
stderr:
Child process exited with exit code 0
stdout: Child Process 2 executed.
Parameters
Here is the description of the parameters used:
157
Node.js
The spawn() method returns streams (stdout & stderr) and it should be used when
the process returns a large volume of data. spawn() starts receiving the response
as soon as the process starts executing.
Example
Create two js files named support.js and master.js:
File: support.js
console.log("Child Process " + process.argv[2] + " executed." );
File: master.js
const fs = require('fs');
const child_process = require('child_process');
158
Node.js
$ node master.js
Parameters
Here is the description of the parameters used:
159
Node.js
Example
Create two js files named support.js and master.js:
File: support.js
console.log("Child Process " + process.argv[2] + " executed." );
File: master.js
const fs = require('fs');
const child_process = require('child_process');
$ node master.js
160
Node.js
161
Node.js
18. PACKAGING
Consider you have a large project consisting of many files. JXcore can pack them
all into a single file to simplify the distribution. This chapter provides a quick
overview of the whole process starting from installing JXcore.
JXcore Installation
Installing JXcore is quite simple. Here we have provided step-by-step instructions
on how to install JXcore on your system. Follow the steps given below:
Step 1
Download the JXcore package from http://jxcore.com/downloads/, as per your
operating system and machine architecture. We downloaded a package for Cenots
running on 64-bit machine.
$ wget https://s3.amazonaws.com/nodejx/jx_rh64.zip
Step 2
Unpack the downloaded file jx_rh64.zip and copy the jx binary into /usr/bin or
may be in any other directory based on your system setup.
$ unzip jx_rh64.zip
$ cp jx_rh64/jx /usr/bin
Step 3
Set your PATH variable appropriately to run jx from anywhere you like.
$ export PATH=$PATH:/usr/bin
Step 4
You can verify your installation by issuing a simple command as shown below. You
should find it working and printing its version number as follows:
$ jx --version
v0.10.32
162
Node.js
To package the above project, you simply need to go inside this directory and
issue the following jx command. Assuming index.js is the entry file for your
Node.js project:
Here you could have used any other package name instead of index. We have
used index because we wanted to keep our main file name as index.jx. However,
the above command will pack everything and will create the following two files:
index.jx This is the binary file having the complete package that is
ready to be shipped to your client or to your production environment.
Launching JX File
Consider your original Node.js project was running as follows:
$ jx index.jx command_line_arguments
163