Node JS
Node JS
js - Quick Guide
Advertisements
Previous Page
Next Page
Node.js - 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 is a platform built on Chrome's JavaScript runtime for easily building fast and scalable
network applications. Node.js uses an event-driven, non-blocking I/O model that makes it
lightweight and efficient, perfect for data-intensive real-time applications that run across
distributed devices.
Node.js is an open source, cross-platform runtime environment for developing server-side and networking
applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on
OS X, Microsoft Windows, and Linux.
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.
Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is, non-
blocking. It essentially means a Node.js based server never waits for an API to return data. The
server moves to the next API after calling it and a notification mechanism of Events of Node.js helps
the server to get a response from the previous API call.
Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in
code execution.
Single Threaded but Highly Scalable − Node.js uses a single threaded model with event looping.
Event mechanism helps the server to respond in a non-blocking way and makes the server highly
scalable as opposed to traditional servers which create limited threads to handle requests. Node.js
uses a single threaded program and the same program can provide service to a much larger number
of requests than traditional servers like Apache HTTP Server.
No Buffering − Node.js applications never buffer any data. These applications simply output the
data in chunks.
Concepts
The following diagram depicts some important parts of Node.js which we will discuss in detail in the
subsequent chapters.
Try the following example using the Live Demo option available at the top right corner of the
below sample code box (on our website) −
Live Demo
console.log("Hello World!");
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
This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit
command, Brief, Epsilon, EMACS, and vim or vi.
Name and version of text editor can vary on different operating systems. 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 contain program source code. The source
files for Node.js programs are typically named with the extension ".js".
Before starting your programming, make sure you have one text editor in place and you have enough
experience to write a computer program, save it in a file, and finally execute it.
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.
Following section guides you on how to install Node.js binary distribution on various OS.
OS Archive name
Windows node-v6.3.1-x64.msi
Linux node-v6.3.1-linux-x86.tar.gz
Mac node-v6.3.1-darwin-x86.tar.gz
SunOS node-v6.3.1-sunos-x86.tar.gz
$ cd /tmp
$ wget http://nodejs.org/dist/v6.3.1/node-v6.3.1-linux-x64.tar.gz
$ tar xvfz node-v6.3.1-linux-x64.tar.gz
$ mkdir -p /usr/local/nodejs
$ mv node-v6.3.1-linux-x64/* /usr/local/nodejs
OS Output
Installation on Windows
Use the MSI file and follow the prompts to install the 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.
Live Demo
console.log("Hello, World!")
Now execute main.js file using Node.js interpreter to see the result −
$ node main.js
If everything is fine with your installation, this should produce the following result −
Hello, World!
Import required modules − We use the require directive to load Node.js modules.
Create server − A server which will listen to client's requests similar to Apache HTTP Server.
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.
response.end('Hello World\n');
}).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.
response.end('Hello World\n');
}).listen(8081);
$ node main.js
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
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 World
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
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.
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)
>
Node.js - NPM
Node Package Manager (NPM) provides two main functionalities −
Command line utility to install Node.js packages, do version management and dependency
management of Node.js packages.
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
−
$ 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.
Globally installed packages/dependencies are stored in system directory. Such dependencies can be used
in CLI (Command Line Interface) function of any node.js but cannot be imported using require() in Node
application directly. Now let's try installing the express module using global installation.
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)
├── proxy-addr@1.0.7 (forwarded@0.1.0, ipaddr.js@0.1.9)
├── send@0.12.1 (destroy@1.0.3, ms@0.7.0, mime@1.3.4)
├── serve-static@1.9.2 (send@0.12.2)
├── accepts@1.2.5 (negotiator@0.5.1, mime-types@2.0.10)
└── type-is@1.6.1 (media-typer@0.3.0, mime-types@2.0.10)
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",
"version": "4.11.2",
"author": {
"email": "tj@vision-media.ca"
},
"contributors": [{
"email": "aaron.heckmann+github@gmail.com"
},
"email": "ciaranj@gmail.com"
},
},
"email": "rauchg@gmail.com"
},
"email": "me@jongleberry.com"
},
"email": "shtylman+expressjs@gmail.com"
},
"email": "hanul@hanul.me"
} ],
"type": "git",
"url": "https://github.com/strongloop/express"
},
"express",
"framework",
"sinatra",
"web",
"rest",
"restful",
"router",
"app",
"api"
],
"dependencies": {
"accepts": "~1.2.3",
"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",
"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": {
},
"files": [
"LICENSE",
"History.md",
"Readme.md",
"index.js",
"lib/"
],
"scripts": {
},
"gitHead": "63ab25579bda70b4927a179b580a9c580b6c7ada",
"bugs": {
"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"
},
"name": "rfeng",
"email": "enjoyjava@gmail.com"
}],
"dist": {
"shasum": "8df3d5a9ac848585f00a0777601823faecd3b148",
"tarball": "https://registry.npmjs.org/express/-/express-4.11.2.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/express/-/express-4.11.2.tgz",
Attributes of Package.json
name − name of the package
dependencies − list of dependencies. NPM automatically installs all the dependencies mentioned
here in the node_module folder of the package.
keywords − keywords
Uninstalling a Module
Use the following command to uninstall a Node.js module.
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.
$ 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.
For example, a function to read a file may start reading file and return the control to the execution
environment immediately so that the next instruction can be executed. Once file I/O is complete, it will call
the callback function while passing the callback function, the content of the file as a parameter. So there is
no blocking or wait for File I/O. This makes Node.js highly scalable, as it can process a high number of
requests without waiting for any function to return results.
var fs = require("fs");
console.log(data.toString());
console.log("Program Ended");
$ node main.js
var fs = require("fs");
console.log(data.toString());
});
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.
Thus, a blocking program executes very much in sequence. From the programming point of view, it is easier
to implement the logic but non-blocking programs do not execute in sequence. In case a program needs to
use any data to be processed, it should be kept within the same block to make it sequential execution.
Event-Driven Programming
Node.js uses events heavily and it is also one of the reasons why Node.js is pretty fast compared to other
similar technologies. As soon as Node starts its server, it simply initiates its variables, declares functions
and then simply waits for the event to occur.
In an event-driven application, there is generally a main loop that listens for events, and then triggers a
callback function when one of those events is detected.
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 −
// Fire an event
eventEmitter.emit('eventName');
Example
Create a js file named main.js with the following code −
Live Demo
console.log('connection succesful.');
eventEmitter.emit('data_received');
eventEmitter.on('connection', connectHandler);
eventEmitter.on('data_received', function() {
eventEmitter.emit('connection');
console.log("Program Ended.");
Now let's try to run the above program and check its output −
$ node main.js
connection successful.
data received successfully.
Program Ended.
var fs = require("fs");
if (err) {
console.log(err.stack);
return;
console.log(data.toString());
});
console.log("Program Ended");
Here fs.readFile() is a async function whose purpose is to read a file. If an error occurs during the read
operation, then the err object will contain the 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!!!!!
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.
EventEmitter provides multiple properties like on and emit. on property is used to bind a function with the
event and emit is used to fire an event.
Methods
Sr.No. Method & Description
addListener(event, listener)
1 Adds a listener at the end of the listeners array for the specified event. No checks are made to see if the listener has
already been added. Multiple calls passing the same combination of event and listener will result in the listener being
added multiple times. Returns emitter, so calls can be chained.
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
2
already been added. Multiple calls passing the same combination of event and listener will result in the listener being
added multiple times. Returns emitter, so calls can be chained.
once(event, listener)
3 Adds a one time listener to the event. This listener is invoked only the next time the event is fired, after which it is
removed. Returns emitter, so calls can be chained.
removeListener(event, listener)
4 Removes a listener from the listener array for the specified event. Caution − It changes the array indices in the
listener array behind the listener. removeListener will remove, at most, one instance of a listener from the listener
array. If any single listener has been added multiple times to the listener array for the specified event, then
removeListener must be called multiple times to remove each instance. Returns emitter, so calls can be chained.
removeAllListeners([event])
Removes all listeners, or those of the specified event. It's not a good idea to remove listeners that were added
5
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 are added for a particular event. This is a
6
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.
8 Execute each of the listeners in order with the supplied arguments. Returns true if the event had listeners, false
otherwise.
Class Methods
Sr.No. Method & Description
listenerCount(emitter, event)
1
Returns the number of listeners for a given event.
Events
Sr.No. Events & Description
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 −
Live Demo
// listener #1
console.log('listner1 executed.');
// listener #2
console.log('listner2 executed.');
eventEmitter.addListener('connection', listner1);
eventEmitter.on('connection', listner2);
(eventEmitter,'connection');
eventEmitter.emit('connection');
eventEmitter.removeListener('connection', listner1);
eventEmitter.emit('connection');
eventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log("Program Ended.");
$ node main.js
Node.js - Buffers
Pure JavaScript is Unicode friendly, but it is not so for binary data. While dealing with TCP streams or the
file system, it's necessary to handle octet streams. Node provides Buffer class which provides instances to
store raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8
heap.
Buffer class is a global class that can be accessed in an application without importing the buffer module.
Creating Buffers
Node Buffer can be constructed in a variety of ways.
Method 1
Following is the syntax to create an uninitiated Buffer of 10 octets −
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 −
var buf = new Buffer("Simply Easy Learning", "utf-8");
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 −
Parameters
Here is the description of the parameters used −
offset − This is the index of the buffer to start writing at. Default value is 0.
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
Live Demo
Octets written : 20
Parameters
Here is the description of the parameters used −
Return Value
This method decodes and returns a string from buffer data encoded using the specified character set
encoding.
Example
Live Demo
buf[i] = i + 97;
abcdefghijklmnopqrstuvwxyz
abcde
abcde
abcde
buf.toJSON()
Return Value
This method returns a JSON-representation of the Buffer instance.
Example
Live Demo
console.log(json);
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
Live Demo
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
Live Demo
if(result < 0) {
} else {
Copy Buffer
Syntax
Following is the syntax of the method to copy a node buffer −
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
Live Demo
//copy a buffer
buffer1.copy(buffer2);
Slice Buffer
Syntax
Following is the syntax of the method to get a sub-buffer of a node buffer −
buf.slice([start][, end])
Parameters
Here is the description of the parameters used −
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
Live Demo
//slicing a buffer
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
Live Demo
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.
Sr.No. Method & Description
1 new Buffer(size)
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
4 Returns the size of the buffer in bytes. Note that this is not necessarily 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.
5 Writes a string to the buffer at offset using the given encoding. offset defaults to 0, encoding defaults to 'utf8'. length
is the number of bytes to write. Returns the number of octets written.
6 Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert
to true to skip validation of value and offset. Defaults to false.
7 Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert
to true to skip validation of value and offset. Defaults to false.
8 Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert
to true to skip validation of value and offset. Defaults to false.
9 Writes a value to the buffer at the specified offset and byteLength. Supports up to 48 bits of accuracy. Set noAssert
to true to skip validation of value and offset. Defaults to false.
10 A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip
validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false.
11 A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip
validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false.
13 A generalized version of all numeric read methods. Supports up to 48 bits of accuracy. Set noAssert to true to skip
validation of offset. It means that the offset may be beyond the end of the buffer. Defaults to false.
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.
Copies data from a region of this buffer to a region in the target buffer even if the target memory region overlaps
19
with the source. If undefined, the targetStart and sourceStart parameters default to 0, while sourceEnd defaults to
buffer.length.
buf.slice([start][, end])
20 Returns a new buffer which references the same memory as the old, 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])
21 Reads an unsigned 8 bit integer from the buffer at the specified offset. Set noAssert to true to skip validation of offset.
It means that the offset may be beyond the end of the buffer. Defaults to false.
buf.readUInt16LE(offset[, noAssert])
22 Reads an unsigned 16-bit integer from the buffer at the specified offset 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.
23 buf.readUInt16BE(offset[, noAssert])
Reads an unsigned 16-bit integer from the buffer at the specified offset 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])
24 Reads an unsigned 32-bit integer from the buffer at the specified offset 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])
25 Reads an unsigned 32-bit integer from the buffer at the specified offset 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])
26 Reads a signed 8-bit integer from the buffer at the specified offset. 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.readInt16LE(offset[, noAssert])
27 Reads a signed 16-bit integer from the buffer at the specified offset 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])
28 Reads a signed 16-bit integer from the buffer at the specified offset 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.readInt32LE(offset[, noAssert])
29 Reads a signed 32-bit integer from the buffer at the specified offset 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])
30 Reads a signed 32-bit integer from the buffer at the specified offset 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])
31 Reads a 32-bit float from the buffer at the specified offset 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.readFloatBE(offset[, noAssert])
32 Reads a 32-bit float from the buffer at the specified offset 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.readDoubleLE(offset[, noAssert])
33 Reads a 64-bit double from the buffer at the specified offset 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.readDoubleBE(offset[, noAssert])
34 Reads a 64-bit double from the buffer at the specified offset 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.
Writes a value to the buffer at the specified offset. Note that the value must be a valid unsigned 8-bit integer. Set
35 noAssert to true to skip validation of value and offset. It means the value may be too large for 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.
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a
36 valid unsigned 16-bit integer. Set noAssert to true to skip validation of value and offset. It 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.
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a
37 valid unsigned 16-bit integer. Set noAssert to true to skip validation of value and offset. It 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 its correctness. Defaults to false.
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a
38 valid unsigned 32-bit integer. Set noAssert to true to skip validation of value and offset. It 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 its correctness. Defaults to false.
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a
39 valid unsigned 32-bit integer. Set noAssert to true to skip validation of value and offset. It 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 its correctness. Defaults to false.
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a
40 valid signed 8-bit integer. Set noAssert to true to skip validation of value and offset. It 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 its correctness. Defaults to false.
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a
42 valid signed 16-bit integer. Set noAssert to true to skip validation of value and offset. It means the value may be too
large for 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.
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a
43 valid signed 32-bit integer. Set noAssert to true to skip validation of value and offset. It 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 its correctness. Defaults to false.
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a
44 valid signed 32-bit integer. Set noAssert to true to skip validation of value and offset. It 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.
Writes a value to the buffer at the specified offset with the specified endian format. Note that the value must be a
45 valid 32-bit float. Set noAssert to true to skip validation of value and offset. It means that 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 its correctness. Defaults to false.
Writes a value to the buffer at the specified offset with the specified endian format. Note, value must be a valid 32-
46 bit float. Set noAssert to true to skip validation of value and offset. It 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 its correctness. Defaults to false.
Writes a value to the buffer at the specified offset with the specified endian format. Note, value must be a valid 64-
47 bit double. Set noAssert to true to skip validation of value and offset. It means that value may be too large for 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.
49 Fills the buffer with the specified value. If the offset (defaults to 0) and end (defaults to buffer.length) are not given,
it will fill the entire buffer.
Class Methods
Sr.No. Method & Description
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])
3 Gives the actual byte length of a string. encoding defaults to 'utf8'. It is not the same as String.prototype.length, since
String.prototype.length returns the number of characters in a string.
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.
Node.js - Streams
What are Streams?
Streams are objects that let you read data from a source or write data to a destination in continuous
fashion. In Node.js, there are four types of streams −
Duplex − Stream which can be used for both read and write operation.
Transform − A type of duplex stream where the output is computed based on input.
Each type of Stream is an EventEmitter instance and throws several events at different instance of times.
For example, some of the commonly used events are −
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.
This tutorial provides a basic understanding of the commonly used operations on Streams.
var fs = require("fs");
readerStream.setEncoding('UTF8');
readerStream.on('data', function(chunk) {
data += chunk;
});
readerStream.on('end',function() {
console.log(data);
});
readerStream.on('error', function(err) {
console.log(err.stack);
});
console.log("Program Ended");
$ node main.js
Verify the Output.
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 −
Live Demo
var fs = require("fs");
writerStream.write(data,'UTF8');
writerStream.end();
writerStream.on('finish', function() {
console.log("Write completed.");
});
writerStream.on('error', function(err) {
console.log(err.stack);
});
console.log("Program Ended");
$ node main.js
Now open output.txt created in your current directory; it should contain the following −
var fs = require("fs");
readerStream.pipe(writerStream);
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");
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");
fs.createReadStream('input.txt.gz')
.pipe(zlib.createGunzip())
.pipe(fs.createWriteStream('input.txt'));
console.log("File Decompressed.");
$ node main.js
var 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
if (err) {
return console.error(err);
});
// Synchronous read
console.log("Program Ended");
$ node main.js
Verify the Output.
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).
Flags
Flags for read/write operations are −
r
1
Open file for reading. An exception occurs if the file does not exist.
r+
2
Open file for reading and writing. An exception occurs if the file does not exist.
rs
3
Open file for reading in synchronous mode.
rs+
4 Open file for reading and writing, asking the OS to open it synchronously. See notes for 'rs' about using this with
caution.
w
5
Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
wx
6
Like 'w' but fails if the path exists.
w+
7
Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
wx+
8
Like 'w+' but fails if path exists.
a
9
Open file for appending. The file is created if it does not exist.
ax
10
Like 'a' but fails if the path exists.
a+
11
Open file for reading and appending. The file is created if it does not exist.
ax+
12
Like 'a+' but fails if the the path exists.
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");
if (err) {
return console.error(err);
});
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.
stats.isFile()
1
Returns true if file type of a simple file.
stats.isDirectory()
2
Returns true if file type of a directory.
stats.isBlockDevice()
3
Returns true if file type of a block device.
stats.isCharacterDevice()
4
Returns true if file type of a character device.
stats.isSymbolicLink()
5
Returns true if file type of a symbolic link.
stats.isFIFO()
6
Returns true if file type of a FIFO.
stats.isSocket()
7
Returns true if file type of asocket.
Example
Let us create a js file named main.js with the following code −
var fs = require("fs");
if (err) {
return console.error(err);
console.log(stats);
});
$ node main.js
Writing a File
Syntax
Following is the syntax of one of the methods to write into a file −
This method will over-write 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.
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 −
Live Demo
var fs = require("fs");
if (err) {
return console.error(err);
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
});
$ node main.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.
position − This is an integer specifying where to begin reading from in the file. If position is null,
data will be read from the current file position.
callback − This is the callback function which gets the three arguments, (err, bytesRead, buffer).
Example
Let us create a js file named main.js with the following code −
var fs = require("fs");
if (err) {
return console.error(err);
if (err){
console.log(err);
console.log(buf.slice(0, bytes).toString());
});
});
$ 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 −
Example
Let us create a js file named main.js having the following code −
var fs = require("fs");
if (err) {
return console.error(err);
if (err) {
console.log(err);
if(bytes > 0) {
console.log(buf.slice(0, bytes).toString());
fs.close(fd, function(err) {
if (err) {
console.log(err);
});
});
});
$ node main.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.
callback − This is the callback function No arguments other than a possible exception are given to
the completion callback.
Example
Let us create a js file named main.js having the following code −
var fs = require("fs");
if (err) {
return console.error(err);
if (err) {
console.log(err);
if (err) {
console.log(err);
if(bytes > 0) {
console.log(buf.slice(0, bytes).toString());
fs.close(fd, function(err) {
if (err) {
console.log(err);
});
});
});
});
$ node main.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 −
callback − This is the callback function No arguments other than a possible exception are given to
the completion callback.
Example
Let us create a js file named main.js having the following code −
var fs = require("fs");
fs.unlink('input.txt', function(err) {
if (err) {
return console.error(err);
});
$ 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 −
callback − This is the callback function No arguments other than a possible exception are given to
the completion callback.
Example
Let us create a js file named main.js having the following code −
var fs = require("fs");
fs.mkdir('/tmp/test',function(err) {
if (err) {
return console.error(err);
});
$ node main.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 −
Example
Let us create a js file named main.js having the following code −
var fs = require("fs");
fs.readdir("/tmp/",function(err, files) {
if (err) {
return console.error(err);
console.log( file );
});
});
$ node main.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 −
callback − This is the callback function No arguments other than a possible exception are given to
the completion callback.
Example
Let us create a js file named main.js having the following code −
var fs = require("fs");
fs.rmdir("/tmp/test",function(err) {
if (err) {
return console.error(err);
fs.readdir("/tmp/",function(err, files) {
if (err) {
return console.error(err);
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.
Sr.No Method & Description
fs.rename(oldPath, newPath, callback)
1
Asynchronous rename(). No arguments other than a possible exception are given to the completion callback.
fs.ftruncateSync(fd, len)
3
Synchronous ftruncate().
fs.truncateSync(path, len)
5
Synchronous truncate().
fs.chmodSync(path, mode)
13
Synchronous chmod().
15 fs.fchmodSync(fd, mode)
Synchronous fchmod().
16 Asynchronous lchmod(). No arguments other than a possible exception are given to the completion callback. Only
available on Mac OS X.
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)
19 Asynchronous lstat(). The callback gets two arguments (err, stats) 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)
20 Asynchronous fstat(). The callback gets two arguments (err, stats) 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.
fs.linkSync(srcpath, dstpath)
25
Synchronous link().
Asynchronous symlink(). No arguments other than a possible exception are given to the completion callback. The
26 type argument can be set to 'dir', 'file', or 'junction' (default is 'file') and is only available on Windows (ignored on
other platforms). Note that Windows junction points require the destination path to be absolute. When using 'junction',
the destination argument will automatically be normalized to absolute path.
Asynchronous realpath(). The callback gets two arguments (err, resolvedPath). May use process.cwd to resolve
29
relative paths. cache is an object literal of mapped paths that can be used to force a specific path resolution or avoid
additional fs.stat calls for known real paths.
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.
fs.rmdirSync(path)
34
Synchronous rmdir().
35 Asynchronous mkdir(2). No arguments other than a possible exception are given to the completion callback. mode
defaults to 0777.
fs.mkdirSync(path[, mode])
36
Synchronous mkdir().
fs.readdir(path, callback)
37 Asynchronous readdir(3). Reads the contents of a directory. The 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().
fs.open(path, flags[, mode], callback)
41
Asynchronous file open.
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.
fs.readFileSync(filename[, options])
56
Synchronous version of fs.readFile. Returns the contents of the filename.
fs.unwatchFile(filename[, listener])
62 Stop watching for changes on filename. If listener is specified, only that 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.
66 Tests a user's permissions for the file specified by path. mode is an optional integer that specifies the accessibility
checks to be performed.
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.
Asynchronous symlink(). No arguments other than a possible exception are given to the completion callback. The
70 type argument can be set to 'dir', 'file', or 'junction' (default is 'file') and is only available on Windows (ignored on
other platforms). Note that Windows junction points require the destination path to be absolute. When using 'junction',
the destination argument will automatically be normalized to absolute path.
__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 −
Live Demo
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 −
Live Demo
$ node main.js
Based on the location of your program, it will print 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 −
Live Demo
function printHello() {
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.
Example
Create a js file named main.js with the following code −
Live Demo
function printHello() {
clearTimeout(t);
$ 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 −
Live Demo
function printHello() {
setInterval(printHello, 2000);
$ node main.js
The above program will execute printHello() after every 2 second. Due to system limitation.
Global Objects
The following table provides a list of other objects which we use frequently in our applications. For a more
detail, you can refer to the official documentation.
Process
2
Used to get information on current process. Provides multiple events related to process activities.
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.
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.
Business − This layer contains the application server which is utilized by the web server to do the
required processing. This layer interacts with the data layer via the database or some external
programs.
Data − This layer contains the databases or any other source of data.
File: server.js
var fs = require('fs');
// Create a server
if (err) {
console.log(err);
} else {
//Page found
response.write(data.toString());
response.end();
});
}).listen(8081);
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
File: client.js
host: 'localhost',
port: '8081',
path: '/index.htm'
};
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
console.log(body);
});
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>
Defines a routing table which is used to perform different actions based on HTTP Method and URL.
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 −
body-parser − This is a node.js middleware for handling JSON, Raw, Text and URL encoded form
data.
cookie-parser − Parse Cookie header and populate req.cookies with an object keyed by the cookie
names.
res.send('Hello World');
})
var server = app.listen(8081, function () {
})
Save the above code in a file named server.js and run it with the following command.
$ node server.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.
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.
res.send('Hello GET');
})
res.send('Hello POST');
})
res.send('Hello DELETE');
})
res.send('Page Listing');
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
})
})
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 screens shots showing different responses for different URLs.
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'));
res.send('Hello World');
})
})
Save the above code in a file named server.js and run it with the following command.
$ node server.js
Now open http://127.0.0.1:8081/images/logo.png in any browser and see observe following result.
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.
<html>
<body>
</form>
</body>
</html>
Let's save above code in index.htm and modify server.js to handle home page requests as well as the input
sent by the HTML form.
app.use(express.static('public'));
})
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(8081, function () {
})
Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate the following form −
First Name:
Last Name:
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>
</body>
</html>
Let's save the above code in index.htm and modify server.js to handle home page requests as well as the
input sent by the HTML form.
app.use(express.static('public'));
})
response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
})
Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate the following form −
First Name:
Last Name:
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>
</head>
<body>
<h3>File Upload:</h3>
enctype = "multipart/form-data">
<br />
</form>
</body>
</html>
Let's save above code in index.htm and modify server.js to handle home page requests as well as file
upload.
var fs = require("fs");
})
console.log(req.files.file.name);
console.log(req.files.file.path);
console.log(req.files.file.type);
if( err ) {
console.log( err );
} else {
response = {
filename:req.files.file.name
};
console.log( response );
});
});
})
})
Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate the following form −
File Upload:
Select a file to upload:
NOTE: This is just dummy form and would not work, but it must work at your server.
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.
app.use(cookieParser())
})
app.listen(8081)
A REST Server simply provides access to resources and REST client accesses and modifies the resources
using HTTP protocol. Here each resource is identified by URIs/ global IDs. REST uses various representation
to represent a resource like text, JSON, XML but JSON is the most popular one.
HTTP methods
Following four HTTP methods are commonly used in REST based architecture.
Web services based on REST Architecture are known as RESTful web services. These webservices uses
HTTP methods to implement the concept of REST architecture. A RESTful web service usually defines a URI,
Uniform Resource Identifier a service, which provides resource representation such as JSON and set of
HTTP Methods.
"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
I'm keeping most of the part of all the examples in the form of hard coding assuming you already know
how to pass values from 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 −
server.js
var fs = require("fs");
console.log( data );
res.end( data );
});
})
var server = app.listen(8081, function () {
})
Now try to access defined API using URL: http://127.0.0.1:8081/listUsers and HTTP Method : GET on local
machine using any REST client. This should produce following result −
You can change given IP address when you will put the solution in production environment.
"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 User
Following API will show you how to add new user in the list. Following is the detail of the new user −
user = {
"user4" : {
"name" : "mohit",
"password" : "password4",
"profession" : "teacher",
"id": 4
You can accept the same input in the form of JSON using Ajax call but for teaching point of view, we are
making it hard coded here. Following is the addUser API to a new user in the database −
server.js
var fs = require("fs");
var user = {
"user4" : {
"name" : "mohit",
"password" : "password4",
"profession" : "teacher",
"id": 4
data["user4"] = user["user4"];
console.log( data );
res.end( JSON.stringify(data));
});
})
var server = app.listen(8081, function () {
})
Now try to access defined API using URL: http://127.0.0.1:8081/addUser and HTTP Method : POST on local
machine using any REST client. This should produce following result −
"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.
server.js
var fs = require("fs");
console.log( user );
res.end( JSON.stringify(user));
});
})
var server = app.listen(8081, function () {
})
Now try to access defined API using URL: http://127.0.0.1:8081/2 and HTTP Method : GET on local machine
using any REST client. This should produce following result −
{"name":"suresh","password":"password2","profession":"librarian","id":2}
Delete User
This API is very similar to addUser API where we receive input data through req.body and then based on
user ID we delete that user from the database. To keep our program simple we assume we are going to
delete user with ID 2.
server.js
var fs = require("fs");
var id = 2;
console.log( data );
res.end( JSON.stringify(data));
});
})
})
Now try to access defined API using URL: http://127.0.0.1:8081/deleteUser and HTTP Method : DELETE on
local machine using any REST client. This should produce following result −
{"user1":{"name":"mahesh","password":"password1","profession":"teacher","id":1},
"user3":{"name":"ramesh","password":"password3","profession":"clerk","id":3}}
Child processes always have three streams child.stdin, child.stdout, and child.stderr which may be
shared with the stdio streams of the parent process.
Node provides child_process module which has the following three major ways to create a child process.
exec − child_process.exec method runs a command in a shell/console and buffers the output.
fork − The child_process.fork method is a special case of the spawn() to create child processes.
Parameters
Here is the description of the parameters used −
o shell (String) Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on
Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On
Windows, command line parsing should be compatible with cmd.exe.)
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
File: master.js
const fs = require('fs');
if (error) {
console.log(error.stack);
});
});
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 −
o customFds (Array) Deprecated File descriptors for the child to use for stdio.
The spawn() method returns streams (stdout &stderr) and it should be used when the process returns a
volume amount 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
const fs = require('fs');
});
});
});
$ node master.js
Parameters
Here is the description of the parameters used −
o silent (Boolean) If true, stdin, stdout, and stderr of the child will be piped to the parent,
otherwise they will be inherited from the parent, see the "pipe" and "inherit" options for
spawn()'s stdio for more details (default is false).
The fork method returns an object with a built-in communication channel in addition to having all the
methods in a normal ChildProcess instance.
Example
Create two js files named support.js and master.js −
File: support.js
File: master.js
const fs = require('fs');
});
}
$ node master.js
Node.js - Packaging
JXcore, which is an open source project, introduces a unique feature for packaging and encryption of
source files and other assets into JX packages.
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 https://github.com/jxcore/jxcore, 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.zipand 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
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.jxp This is an intermediate file which contains the complete project detail needed to compile
the project.
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