0% found this document useful (0 votes)
234 views60 pages

Nodejs Material

Node.js is an open source server environment that runs JavaScript on the server side. It uses asynchronous programming and non-blocking I/O, which allows it to handle multiple requests at once without waiting for slow operations like file access. Node.js files contain code that runs when certain events occur on the server, like an HTTP request. These files are run using the Node.js command line interface. A "Hello World" example demonstrates creating a Node.js file that displays "Hello World" when the server is accessed on a specific port in a web browser.

Uploaded by

PATEL POOJAN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
234 views60 pages

Nodejs Material

Node.js is an open source server environment that runs JavaScript on the server side. It uses asynchronous programming and non-blocking I/O, which allows it to handle multiple requests at once without waiting for slow operations like file access. Node.js files contain code that runs when certain events occur on the server, like an HTTP request. These files are run using the Node.js command line interface. A "Hello World" example demonstrates creating a Node.js file that displays "Hello World" when the server is accessed on a specific port in a web browser.

Uploaded by

PATEL POOJAN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

What is Node.js?

• Node.js is an open source server environment


• Node.js is free
• Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X,
etc.)
• Node.js uses JavaScript on the server

Why Node.js?
Node.js uses asynchronous programming!

A common task for a web server can be to open a file on the server and
return the content to the client.

Here is how PHP or ASP handles a file request:

1. Sends the task to the computer's file system.


2. Waits while the file system opens and reads the file.
3. Returns the content to the client.
4. Ready to handle the next request.

Here is how Node.js handles a file request:

1. Sends the task to the computer's file system.


2. Ready to handle the next request.
3. When the file system has opened and read the file, the server returns
the content to the client.

Node.js eliminates the waiting, and simply continues with the next request.

Node.js runs single-threaded, non-blocking, asynchronously programming,


which is very memory efficient.

What Can Node.js Do?


• Node.js can generate dynamic page content
• Node.js can create, open, read, write, delete, and close files on the
server
• Node.js can collect form data
• Node.js can add, delete, modify data in your database
What is a Node.js File?
• Node.js files contain tasks that will be executed on certain events
• A typical event is someone trying to access a port on the server
• Node.js files must be initiated on the server before having any effect
• Node.js files have extension ".js"

Download Node.js
The official Node.js website has installation instructions for
Node.js: https://nodejs.org

Getting Started
Once you have downloaded and installed Node.js on your computer, let's try
to display "Hello World" in a web browser.

Create a Node.js file named "myfirst.js", and add the following code:

myfirst.js

var http = require('http');

http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);

Save the file on your computer: C:\Users\Your Name\myfirst.js

The code tells the computer to write "Hello World!" if anyone (e.g. a web
browser) tries to access your computer on port 8080.

For now, you do not have to understand the code. It will be explained later.

Command Line Interface


Node.js files must be initiated in the "Command Line Interface" program of
your computer.

How to open the command line interface on your computer depends on the
operating system. For Windows users, press the start button and look for
"Command Prompt", or simply write "cmd" in the search field.

Navigate to the folder that contains the file "myfirst.js", the command line
interface window should look something like this:

C:\Users\Your Name>_

Initiate the Node.js File


The file you have just created must be initiated by Node.js before any action
can take place.

Start your command line interface, write node myfirst.js and hit enter:

Initiate "myfirst.js":

C:\Users\Your Name>node myfirst.js

Now, your computer works as a server!

If anyone tries to access your computer on port 8080, they will get a "Hello
World!" message in return!

Start your internet browser, and type in the address: http://localhost:8080

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.
It is used in synchronous way when the destination is a file or a terminal and in
asynchronous way when the destination is a pipe.

Console Methods
Following is a list of methods available with the console global object.
Sr.No. Method & Description

1
console.log([data][, ...])
Prints to stdout with newline. This function can take multiple arguments in a printf()-
like way.

2
console.info([data][, ...])
Prints to stdout with newline. This function can take multiple arguments in a printf()-
like way.

3
console.error([data][, ...])
Prints to stderr with newline. This function can take multiple arguments in a printf()-
like way.

4
console.warn([data][, ...])
Prints to stderr with newline. This function can take multiple arguments in a printf()-
like way

5
console.dir(obj[, options])
Uses util.inspect on obj and prints resulting string to stdout.

6
console.time(label)
Mark a time.

7
console.timeEnd(label)
Finish timer, record output.

8
console.trace(message[, ...])
Print to stderr 'Trace :', followed by the formatted message and stack trace to the
current position.

9
console.assert(value[, message][, ...])
Similar to assert.ok(), but the error message is formatted as util.format(message...).

Example
Let us create a js file named main.js with the following code −
console.info("Program Started");

var counter = 10;


console.log("Counter: %d", counter);

console.time("Getting data");
//
// Do some processing here...
//
console.timeEnd('Getting data');

console.info("Program Ended")

Now run the main.js to see the result −


node main.js
Verify the Output.
Program Started
Counter: 10
Getting data: 0ms
Program Ended

What is Callback?
Callback is an asynchronous equivalent for a function. A callback function is called at
the completion of a given task. Node makes heavy use of callbacks. All the APIs of
Node are written in such a way that they support callbacks.
For example, a function to read a file may start reading file and return the control to
the execution environment immediately so that the next instruction can be executed.
Once file I/O is complete, it will call the callback function while passing the callback
function, the content of the file as a parameter. So there is no blocking or wait for File
I/O. This makes Node.js highly scalable, as it can process a high number of requests
without waiting for any function to return results.

Blocking Code Example


Create a text file named input.txt with the following content −
XYZ Point is giving self learning content
to teach the world in simple and easy way!!!!!
Create a js file named main.js with the following code −
var fs = require("fs");
var data = fs.readFileSync('input.txt');

console.log(data.toString());
console.log("Program Ended");
Now run the main.js to see the result −
$ node main.js
Verify the Output.
XYZ is giving self learning content
to teach the world in simple and easy way!!!!!
Program Ended

Non-Blocking Code Example


Create a text file named input.txt with the following content.
XYZ is giving self learning content
to teach the world in simple and easy way!!!!!

Update main.js to have the following code −


var fs = require("fs");

fs.readFile('input.txt', function (err, data) {


if (err) return console.error(err);
console.log(data.toString());
});

console.log("Program Ended");

Now run the main.js to see the result −


$ node main.js
Verify the Output.
Program Ended
XYZ 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.

Node.js is a single-threaded application, but it can support concurrency via the


concept of event and callbacks. Every API of Node.js is asynchronous and being
single-threaded, they use async function calls to maintain concurrency. Node uses
observer pattern. Node thread keeps an event loop and whenever a task gets
completed, it fires the corresponding event which signals the event-listener function
to execute.

Event-Driven Programming
Node.js uses events heavily and it is also one of the reasons why Node.js is pretty
fast compared to other similar technologies. As soon as Node starts its server, it
simply initiates its variables, declares functions and then simply waits for the event to
occur.
In an event-driven application, there is generally a main loop that listens for events,
and then triggers a callback function when one of those events is detected.

Although events look quite similar to callbacks, the difference lies in the fact that
callback functions are called when an asynchronous function returns its result,
whereas event handling works on the observer pattern. The functions that listen to
events act as Observers. Whenever an event gets fired, its listener function starts
executing. Node.js has multiple in-built events available through events module and
EventEmitter class which are used to bind events and event-listeners as follows −
// Import events module
var events = require('events');

// Create an eventEmitter object


var eventEmitter = new events.EventEmitter();
Following is the syntax to bind an event handler with an event −
// Bind event and event handler as follows
eventEmitter.on('eventName', eventHandler);
We can fire an event programmatically as follows −
// Fire an event
eventEmitter.emit('eventName');

Example
Create a js file named main.js with the following code −
// Import events module
var events = require('events');

// Create an eventEmitter object


var eventEmitter = new events.EventEmitter();

// Create an event handler as follows


var connectHandler = function connected() {
console.log('connection succesful.');

// Fire the data_received event


eventEmitter.emit('data_received');
}

// Bind the connection event with the handler


eventEmitter.on('connection', connectHandler);

// Bind the data_received event with the anonymous function


eventEmitter.on('data_received', function() {
console.log('data received succesfully.');
});

// Fire the connection event


eventEmitter.emit('connection');

console.log("Program Ended.");

Now let's try to run the above program and check its output −
$ node main.js
IT should produce the following result −
connection successful.
data received successfully.
Program Ended.

How Node Applications Work?


In Node Application, any async function accepts a callback as the last parameter and
a callback function accepts an error as the first parameter. Let's revisit the previous
example again. Create a text file named input.txt with the following content.
XYZ is giving self learning content
to teach the world in simple and easy way!!!!!

Create a js file named main.js having the following code −


var fs = require("fs");

fs.readFile('input.txt', function (err, data) {


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
XYZ is giving self learning content
to teach the world in simple and easy way!!!!!

Node.js Timer
Node.js Timer functions are global functions. You don't need to use require()
function in order to use timer functions. Let's see the list of timer functions.

Set timer functions:

o setImmediate(): It is used to execute setImmediate.


o setInterval(): It is used to define a time interval.
o setTimeout(): ()- It is used to execute a one-time callback after delay
milliseconds.

Clear timer functions:

o clearImmediate(immediateObject): It is used to stop an


immediateObject, as created by setImmediate
o clearInterval(intervalObject): It is used to stop an intervalObject, as
created by setInterval
o clearTimeout(timeoutObject): It prevents a timeoutObject, as created by
setTimeout

Node.js Timer setInterval() Example


This example will set a time interval of 1000 millisecond and the specified comment
will be displayed after every 1000 millisecond until you terminate.

File: timer1.js

1. setInterval(function() {
2. console.log("setInterval: Hey! 1 millisecond completed!..");
3. }, 1000);
Open Node.js command prompt and run the following code:

1. node timer1.js

File: timer5.js

1. var i =0;
2. console.log(i);
3. setInterval(function(){
4. i++;
5. console.log(i);
6. }, 1000);

Open Node.js command prompt and run the following code:

1. node timer5.js

Node.js Timer setTimeout() Example


File: timer1.js
1. setTimeout(function() {
2. console.log("setTimeout: Hey! 1000 millisecond completed!..");
3. }, 1000);

Open Node.js command prompt and run the following code:

1. node timer1.js

This example shows time out after every 1000 millisecond without setting a time
interval. This example uses the recursion property of a function.

File: timer2.js

1. var recursive = function () {


2. console.log("Hey! 1000 millisecond completed!..");
3. setTimeout(recursive,1000);
4. }
5. recursive();

Open Node.js command prompt and run the following code:

1. node timer2.js

Node.js setInterval(), setTimeout() and


clearTimeout()
Let's see an example to use clearTimeout() function.

File: timer3.js

1. function welcome () {
2. console.log("Welcome to JavaTpoint!");
3. }
4. var id1 = setTimeout(welcome,1000);
5. var id2 = setInterval(welcome,1000);
6. clearTimeout(id1);
7. //clearInterval(id2);

Open Node.js command prompt and run the following code:

1. node timer3.js

You can see that the above example is recursive in nature. It will terminate after
one step if you use ClearInterval.

Node.js setInterval(), setTimeout() and clearInterval()


Let's see an example to use clearInterval() function.

File: timer3.js

1. function welcome () {
2. console.log("Welcome to JavaTpoint!");
3. }
4. var id1 = setTimeout(welcome,1000);
5. var id2 = setInterval(welcome,1000);
6. //clearTimeout(id1);
7. clearInterval(id2);

Open Node.js command prompt and run the following code:

1. node timer3.js
Error Handlling

Errors in Node.js are handled through exceptions.

Creating exceptions
An exception is created using the throw keyword:

throw value

As soon as JavaScript executes this line, the normal program flow is halted and the
control is held back to the nearest exception handler.

Usually in client-side code value can be any JavaScript value including a string, a
number or an object.

In Node.js, we don't throw strings, we just throw Error objects.

Error objects
An error object is an object that is either an instance of the Error object, or extends
the Error class, provided in the Error core module:

throw new Error('Ran out of coffee')

or

class NotEnoughCoffeeError extends Error {


//...
}
throw new NotEnoughCoffeeError()

Handling exceptions
An exception handler is a try/catch statement.
Any exception raised in the lines of code included in the try block is handled in the
corresponding catch block:

try {
//lines of code
} catch (e) {}

e in this example is the exception value.

You can add multiple handlers, that can catch different kinds of errors.

Catching uncaught exceptions


If an uncaught exception gets thrown during the execution of your program, your
program will crash.

To solve this, you listen for the uncaughtException event on the process object:

process.on('uncaughtException', err => {


console.error('There was an uncaught error', err)
process.exit(1) //mandatory (as per the Node.js docs)
})

You don't need to import the process core module for this, as it's automatically
injected.

Exceptions with promises


Using promises you can chain different operations, and handle errors at the end:

doSomething1()
.then(doSomething2)
.then(doSomething3)
.catch(err => console.error(err))

How do you know where the error occurred? You don't really know, but you can
handle errors in each of the functions you call (doSomethingX), and inside the error
handler throw a new error, that's going to call the outside catch handler:

const doSomething1 = () => {


//...
try {
//...
} catch (err) {
//... handle it locally
throw new Error(err.message)
}
//...
}

To be able to handle errors locally without handling them in the function we call, we
can break the chain you can create a function in each then() and process the
exception:

doSomething1()
.then(() => {
return doSomething2().catch(err => {
//handle error
throw err //break the chain!
})
})
.then(() => {
return doSomething3().catch(err => {
//handle error
throw err //break the chain!
})
})
.catch(err => console.error(err))

Error handling with async/await


Using async/await, you still need to catch errors, and you do it this way:

async function someFunction() {


try {
await someOtherFunction()
} catch (err) {
console.error(err.message)
}
Buffers

Pure JavaScript is Unicode friendly, but it is not so for binary data. While dealing with
TCP streams or the file system, it's necessary to handle octet streams. Node provides
Buffer class which provides instances to store raw data similar to an array of integers
but corresponds to a raw memory allocation outside the V8 heap.

Buffer class is a global class that can be accessed in an application without importing
the buffer module.

Creating Buffers
Node Buffer can be constructed in a variety of ways.
Method 1
Following is the syntax to create an uninitiated Buffer of 10 octets −
var buf = new Buffer(10);
Method 2
Following is the syntax to create a Buffer from a given array −
var buf = new Buffer([10, 20, 30, 40, 50]);
Method 3
Following is the syntax to create a Buffer from a given string and optionally encoding
type −
var buf = new Buffer("Simply Easy Learning", "utf-8");
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 −
buf.write(string[, offset][, length][, encoding])
Parameters
Here is the description of the parameters used −
• string − This is the string data to be written to buffer.
• offset − This is the index of the buffer to start writing at. Default value is 0.
• length − This is the number of bytes to write. Defaults to buffer.length.
• encoding − Encoding to use. 'utf8' is the default encoding.
Return Value
This method returns the number of octets written. If there is not enough space in the
buffer to fit the entire string, it will write a part of the string.
Example
buf = new Buffer(256);
len = buf.write("Simply Easy Learning");

console.log("Octets written : "+ len);

When the above program is executed, it produces the following result −


Octets written : 20

Reading from Buffers


Syntax
Following is the syntax of the method to read data from a Node Buffer −
buf.toString([encoding][, start][, end])
Parameters
Here is the description of the parameters used −
• encoding − Encoding to use. 'utf8' is the default encoding.
• start − Beginning index to start reading, defaults to 0.
• end − End index to end reading, defaults is complete buffer.
Return Value
This method decodes and returns a string from buffer data encoded using the
specified character set 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

When the above program is executed, it produces the following result −


abcdefghijklmnopqrstuvwxyz
abcde
abcde
abcde
Convert Buffer to JSON
Syntax
Following is the syntax of the method to convert a Node Buffer into JSON object −
buf.toJSON()
Return Value
This method returns a JSON-representation of the Buffer instance.
Example
var buf = new Buffer('Simply Easy Learning');
var json = buf.toJSON(buf);

console.log(json);

When the above program is executed, it produces the following result −


{ type: 'Buffer',
data:
[
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 −
• list − Array List of Buffer objects to be concatenated.
• totalLength − This is the total length of the buffers when concatenated.
Return Value
This method returns a Buffer instance.
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());

When the above program is executed, it produces the following result −


buffer3 content: TutorialsPoint Simply Easy Learning

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);
}

When the above program is executed, it produces the following result −


ABC comes before ABCD
Copy Buffer
Syntax
Following is the syntax of the method to copy a node buffer −
buf.copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd])
Parameters
Here is the description of the parameters used −
• targetBuffer − Buffer object where buffer will be copied.
• targetStart − Number, Optional, Default: 0
• sourceStart − Number, Optional, Default: 0
• sourceEnd − Number, Optional, Default: buffer.length
Return Value
No return value. Copies data from a region of this buffer to a region in the target buffer
even if the target memory region overlaps with the source. If undefined, the
targetStart and sourceStart parameters default to 0, while sourceEnd defaults to
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());

When the above program is executed, it produces the following result −


buffer2 content: ABC

Slice Buffer
Syntax
Following is the syntax of the method to get a sub-buffer of a node buffer −
buf.slice([start][, end])
Parameters
Here is the description of the parameters used −
• start − Number, Optional, Default: 0
• end − Number, Optional, Default: buffer.length
Return Value
Returns a new buffer which references the same memory as the old one, but offset
and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes.
Negative indexes start from the end of the buffer.
Example
var buffer1 = new Buffer('TutorialsPoint');

//slicing a buffer
var buffer2 = buffer1.slice(0,9);
console.log("buffer2 content: " + buffer2.toString());

When the above program is executed, it produces the following result −


buffer2 content: Tutorials

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);

When the above program is executed, it produces following result −


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.

Class Methods
Sr.No. Method & Description

1
Buffer.isEncoding(encoding)
Returns true if the encoding is a valid encoding argument, false otherwise.

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

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

5
Buffer.compare(buf1, buf2)
The same as buf1.compare(buf2). Useful for sorting an array of buffers.

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 −
• Readable − Stream which is used for read operation.
• Writable − Stream which is used for write operation.
• Duplex − Stream which can be used for both read and write operation.
• Transform − A type of duplex stream where the output is computed based on
input.
Each type of Stream is an EventEmitter instance and throws several events at
different instance of times. For example, some of the commonly used events are −
• data − This event is fired when there is data is available to read.
• end − This event is fired when there is no more data to read.
• error − This event is fired when there is any error receiving or writing data.
• finish − This event is fired when all the data has been flushed to underlying
system.
This tutorial provides a basic understanding of the commonly used operations on
Streams.

Reading from a Stream


Create a text file named input.txt having the following content −
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Create a js file named main.js with the following code −
var fs = require("fs");
var data = '';

// Create a readable stream


var readerStream = fs.createReadStream('input.txt');

// Set the encoding to be utf8.


readerStream.setEncoding('UTF8');

// Handle stream events --> data, end, and error


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");

Now run the main.js to see the result −


$ 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 −
var fs = require("fs");
var data = 'Simply Easy Learning';

// Create a writable stream


var writerStream = fs.createWriteStream('output.txt');

// Write the data to stream with encoding to be utf8


writerStream.write(data,'UTF8');

// Mark the end of file


writerStream.end();

// Handle stream events --> finish, and error


writerStream.on('finish', function() {
console.log("Write completed.");
});

writerStream.on('error', function(err) {
console.log(err.stack);
});

console.log("Program Ended");

Now run the main.js to see the result −


$ node main.js
Verify the Output.
Program Ended
Write completed.
Now open output.txt created in your current directory; it should contain the following

Simply Easy Learning

Piping the Streams


Piping is a mechanism where we provide the output of one stream as the input to
another stream. It is normally used to get data from one stream and to pass the output
of that stream to another stream. There is no limit on piping operations. Now we'll
show a piping example for reading from one file and writing it to another file.
Create a js file named main.js with the following code −
var fs = require("fs");

// Create a readable stream


var readerStream = fs.createReadStream('input.txt');

// Create a writable stream


var writerStream = fs.createWriteStream('output.txt');

// Pipe the read and write operations


// read input.txt and write data to output.txt
readerStream.pipe(writerStream);

console.log("Program Ended");

Now run the main.js to see the result −


$ node main.js
Verify the Output.
Program Ended
Open output.txt created in your current directory; it should contain the following −
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

Chaining the Streams


Chaining is a mechanism to connect the output of one stream to another stream and
create a chain of multiple stream operations. It is normally used with piping
operations. Now we'll use piping and chaining to first compress a file and then
decompress the same.
Create a js file named main.js with the following code −
var fs = require("fs");
var zlib = require('zlib');

// Compress the file input.txt to input.txt.gz


fs.createReadStream('input.txt')
.pipe(zlib.createGzip())
.pipe(fs.createWriteStream('input.txt.gz'));

console.log("File Compressed.");

Now run the main.js to see the result −


$ node main.js
Verify the Output.
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');

// Decompress the file input.txt.gz to input.txt


fs.createReadStream('input.txt.gz')
.pipe(zlib.createGunzip())
.pipe(fs.createWriteStream('input.txt'));

console.log("File Decompressed.");

Now run the main.js to see the result −


$ node main.js
Verify the Output.
File Decompressed.

Node.js - File System


Node implements File I/O using simple wrappers around standard POSIX functions.
The Node File System (fs) module can be imported using the following syntax −
var fs = require("fs")

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 −
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Let us create a js file named main.js with the following code −
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());

console.log("Program Ended");

Now run the main.js to see the result −


$ node main.js
Verify the Output.
Synchronous read: Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

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 −
fs.open(path, flags[, mode], callback)
Parameters
Here is the description of the parameters used −
• path − This is the string having file name including path.
• flags − Flags indicate the behavior of the file to be opened. All possible values
have been mentioned below.
• mode − It sets the file mode (permission and sticky bits), but only if the file was
created. It defaults to 0666, readable and writeable.
• callback − This is the callback function which gets two arguments (err, fd).

Flags
Flags for read/write operations are −

Sr.No. Flag & Description

1
r
Open file for reading. An exception occurs if the file does not exist.

2
r+
Open file for reading and writing. An exception occurs if the file does not exist.

3
rs
Open file for reading in synchronous mode.

4
rs+
Open file for reading and writing, asking the OS to open it synchronously. See
notes for 'rs' about using this with caution.

5
w
Open file for writing. The file is created (if it does not exist) or truncated (if it exists).

6
wx
Like 'w' but fails if the path exists.
7
w+
Open file for reading and writing. The file is created (if it does not exist) or
truncated (if it exists).

8
wx+
Like 'w+' but fails if path exists.

9
a
Open file for appending. The file is created if it does not exist.

10
ax
Like 'a' but fails if the path exists.

11
a+
Open file for reading and appending. The file is created if it does not exist.

12
ax+
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");

// Asynchronous - Opening File


console.log("Going to open file!");
fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("File opened successfully!");
});

Now run the main.js to see the result −


$ node main.js
Verify the Output.
Going to open file!
File opened successfully!
Get File Information
Syntax
Following is the syntax of the method to get the information about a file −
fs.stat(path, callback)
Parameters
Here is the description of the parameters used −
• path − This is the string having file name including path.
• callback − This is the callback function which gets two arguments (err, stats)
where stats is an object of fs.Stats type which is printed below in the example.
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.

Sr.No. Method & Description

1
stats.isFile()
Returns true if file type of a simple file.

2
stats.isDirectory()
Returns true if file type of a directory.

3
stats.isBlockDevice()
Returns true if file type of a block device.

4
stats.isCharacterDevice()
Returns true if file type of a character device.

5
stats.isSymbolicLink()
Returns true if file type of a symbolic link.

6
stats.isFIFO()
Returns true if file type of a FIFO.

7
stats.isSocket()
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");

console.log("Going to get file info!");


fs.stat('input.txt', function (err, stats) {
if (err) {
return console.error(err);
}
console.log(stats);
console.log("Got file info successfully!");

// Check file type


console.log("isFile ? " + stats.isFile());
console.log("isDirectory ? " + stats.isDirectory());
});

Now run the main.js to see the result −


$ node main.js
Verify the Output.
Going to get file info!
{
dev: 1792,
mode: 33188,
nlink: 1,
uid: 48,
gid: 48,
rdev: 0,
blksize: 4096,
ino: 4318127,
size: 97,
blocks: 8,
atime: Sun Mar 22 2015 13:40:00 GMT-0500 (CDT),
mtime: Sun Mar 22 2015 13:40:57 GMT-0500 (CDT),
ctime: Sun Mar 22 2015 13:40:57 GMT-0500 (CDT)
}
Got file info successfully!
isFile ? true
isDirectory ? false

Writing a File
Syntax
Following is the syntax of one of the methods to write into a file −
fs.writeFile(filename, data[, options], callback)
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.
• data − This is the String or Buffer to be written into the file.
• options − The third parameter is an object which will hold {encoding, mode,
flag}. By default. encoding is utf8, mode is octal value 0666. and flag is 'w'
• callback − This is the callback function which gets a single parameter err that
returns an error in case of any writing error.
Example
Let us create a js file named main.js having the following code −
var fs = require("fs");

console.log("Going to write into existing file");


fs.writeFile('input.txt', 'Simply Easy Learning!', function(err)
{
if (err) {
return console.error(err);
}

console.log("Data written successfully!");


console.log("Let's read newly written data");

fs.readFile('input.txt', function (err, data) {


if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
});

Now run the main.js to see the result −


$ node main.js
Verify the Output.
Going to write into existing file
Data written successfully!
Let's read newly written data
Asynchronous read: Simply Easy Learning!

Reading a File
Syntax
Following is the syntax of one of the methods to read from a file −
fs.read(fd, buffer, offset, length, position, callback)
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 −
• fd − This is the file descriptor returned by fs.open().
• buffer − This is the buffer that the data will be written to.
• offset − This is the offset in the buffer to start writing at.
• length − This is an integer specifying the number of bytes to read.
• position − This is an integer specifying where to begin reading from in the file.
If position is null, data will be read from the current file position.
• callback − This is the callback function which gets the three arguments, (err,
bytesRead, buffer).
Example
Let us create a js file named main.js with the following code −
var fs = require("fs");
var buf = new Buffer(1024);

console.log("Going to open an existing file");


fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("File opened successfully!");
console.log("Going to read the file");

fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){


if (err){
console.log(err);
}
console.log(bytes + " bytes read");

// Print only read bytes to avoid junk.


if(bytes > 0){
console.log(buf.slice(0, bytes).toString());
}
});
});

Now run the main.js to see the result −


$ node main.js
Verify the Output.
Going to open an existing file
File opened successfully!
Going to read the file
97 bytes read
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

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 −
• fd − This is the file descriptor returned by file fs.open() method.
• 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");
var buf = new Buffer(1024);

console.log("Going to open an existing file");


fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("File opened successfully!");
console.log("Going to read the file");

fs.read(fd, buf, 0, buf.length, 0, function(err, bytes) {


if (err) {
console.log(err);
}

// Print only read bytes to avoid junk.


if(bytes > 0) {
console.log(buf.slice(0, bytes).toString());
}

// Close the opened file.


fs.close(fd, function(err) {
if (err) {
console.log(err);
}
console.log("File closed successfully.");
});
});
});
Now run the main.js to see the result −
$ node main.js
Verify the Output.
Going to open an existing file
File opened successfully!
Going to read the file
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

File closed successfully.

Truncate a File
Syntax
Following is the syntax of the method to truncate an opened file −
fs.ftruncate(fd, len, callback)
Parameters
Here is the description of the parameters used −
• fd − This is the file descriptor returned by fs.open().
• len − This is the length of the file after which the file will be truncated.
• callback − This is the callback function No arguments other than a possible
exception are given to the completion callback.
Example
Let us create a js file named main.js having the following code −
var fs = require("fs");
var buf = new Buffer(1024);

console.log("Going to open an existing file");


fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("File opened successfully!");
console.log("Going to truncate the file after 10 bytes");

// Truncate the opened file.


fs.ftruncate(fd, 10, function(err) {
if (err) {
console.log(err);
}
console.log("File truncated successfully.");
console.log("Going to read the same file");

fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){


if (err) {
console.log(err);
}

// Print only read bytes to avoid junk.


if(bytes > 0) {
console.log(buf.slice(0, bytes).toString());
}

// Close the opened file.


fs.close(fd, function(err) {
if (err) {
console.log(err);
}
console.log("File closed successfully.");
});
});
});
});

Now run the main.js to see the result −


$ node main.js
Verify the Output.
Going to open an existing file
File opened successfully!
Going to truncate the file after 10 bytes
File truncated successfully.
Going to read the same file
Tutorials
File closed successfully.

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 −
• path − This is the file name including path.
• callback − This is the callback function No arguments other than a possible
exception are given to the completion callback.
Example
Let us create a js file named main.js having the following code −
var fs = require("fs");

console.log("Going to delete an existing file");


fs.unlink('input.txt', function(err) {
if (err) {
return console.error(err);
}
console.log("File deleted successfully!");
});

Now run the main.js to see the result −


$ node main.js
Verify the Output.
Going to delete an existing file
File deleted successfully!

Create a Directory
Syntax
Following is the syntax of the method to create a directory −
fs.mkdir(path[, mode], callback)
Parameters
Here is the description of the parameters used −
• path − This is the directory name including path.
• mode − This is the directory permission to be set. Defaults to 0777.
• callback − This is the callback function No arguments other than a possible
exception are given to the completion callback.
Example
Let us create a js file named main.js having the following code −
var fs = require("fs");

console.log("Going to create directory /tmp/test");


fs.mkdir('/tmp/test',function(err) {
if (err) {
return console.error(err);
}
console.log("Directory created successfully!");
});

Now run the main.js to see the result −


$ node main.js
Verify the Output.
Going to create directory /tmp/test
Directory created successfully!

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 −
• path − This is the directory name including path.
• callback − This is the callback function which gets two arguments (err, files)
where files is an array of the names of the files in the directory excluding '.' and
'..'.
Example
Let us create a js file named main.js having the following code −
var fs = require("fs");

console.log("Going to read directory /tmp");


fs.readdir("/tmp/",function(err, files) {
if (err) {
return console.error(err);
}
files.forEach( function (file) {
console.log( file );
});
});

Now run the main.js to see the result −


$ node main.js
Verify the Output.
Going to read directory /tmp
ccmzx99o.out
ccyCSbkF.out
employee.ser
hsperfdata_apache
test
test.txt

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 −
• path − This is the directory name including path.
• callback − This is the callback function No arguments other than a possible
exception are given to the completion callback.
Example
Let us create a js file named main.js having the following code −
var fs = require("fs");

console.log("Going to delete directory /tmp/test");


fs.rmdir("/tmp/test",function(err) {
if (err) {
return console.error(err);
}
console.log("Going to read directory /tmp");

fs.readdir("/tmp/",function(err, files) {
if (err) {
return console.error(err);
}
files.forEach( function (file) {
console.log( file );
});
});
});

Now run the main.js to see the result −


$ node main.js
Verify the Output.
Going to read directory /tmp
ccmzx99o.out
ccyCSbkF.out
employee.ser
hsperfdata_apache
test.txt

Web Module
What is a Web Server?
A Web Server is a software application which handles HTTP requests sent by the
HTTP client, like web browsers, and returns web pages in response to the clients.
Web servers usually deliver html documents along with images, style sheets, and
scripts.
Most of the web servers support server-side scripts, using scripting languages or
redirecting the task to an application server which retrieves data from a database and
performs complex logic and then sends a result to the HTTP client through the Web
server.
Apache web server is one of the most commonly used web servers. It is an open
source project.

Web Application Architecture


A Web application is usually divided into four layers −

• Client − This layer consists of web browsers, mobile browsers or applications


which can make HTTP requests to the web server.
• Server − This layer has the Web server which can intercept the requests made
by the clients and pass them the response.
• Business − This layer contains the application server which is utilized by the
web server to do the required processing. This layer interacts with the data
layer via the database or some external programs.
• Data − This layer contains the databases or any other source of data.

Creating a Web Server using Node


Node.js provides an http module which can be used to create an HTTP client of a
server. Following is the bare minimum structure of the HTTP server which listens at
8081 port.
Create a js file named server.js −
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;

// Print the name of the file for which request is made.


console.log("Request for " + pathname + " received.");

// Read the requested file content from file system


fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);

// HTTP Status: 404 : NOT FOUND


// Content Type: text/plain
response.writeHead(404, {'Content-Type': 'text/html'});
} else {
//Page found
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/html'});

// Write the content of the file to response body


response.write(data.toString());
}

// Send the response body


response.end();
});
}).listen(8081);

// Console will print the message


console.log('Server running at http://127.0.0.1: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>

Now let us run the server.js to see the result −


$ node server.js
Verify the Output.
Server running at http://127.0.0.1:8081/

Make a request to Node.js server


Open http://127.0.0.1:8081/index.htm in any browser to see the following result.

Verify the Output at server end.


Server running at http://127.0.0.1:8081/
Request for /index.htm received.

Creating Web client using Node


A web client can be created using http module. Let's check the following example.
Create a js file named client.js −
File: client.js
var http = require('http');

// Options to be used by request


var options = {
host: 'localhost',
port: '8081',
path: '/index.htm'
};

// Callback function is used to deal with response


var callback = function(response) {
// Continuously update stream with data
var body = '';
response.on('data', function(data) {
body += data;
});

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
Verify the Output.
<html>
<head>
<title>Sample Page</title>
</head>

<body>
Hello World!
</body>
</html>
Verify the Output at server end.
Server running at http://127.0.0.1:8081/
Request for /index.htm received.

Node.js Debugging
Node.js Debugging: Debugging is a concept to identify and remove errors
from software applications. In this article, we will learn about the technique to
debug a Node.js application.
Why not to use console.log()?
Using console.log to debug the code generally dives into an infinite loop of
“stopping the app and adding a console.log, and start the app again”
operations. Besides slowing down the development of the app, it also makes
the writing dirty and creates unnecessary code. Finally, trying to log out
variables alongside with the noise of other potential logging operations, may
make the process of debugging difficult when attempting to find the values
you are debugging.
How to debug?
Mostly we used console.log() but as mentioned above, it is not always a
good practice. We can use a V8 inspector for it.
Steps for debugging:
1. Write the following code in the terminal window as shown below:
node --inspect-brk-filename.js

2. Open your Chrome browser and write inspect as shown below:


3. Now click on Open Dedicated DevTools for Node.

4. Now, click on the Node.js icon. The terminal will show the following
message:

Other tools to help launch a DevTools window:


june07.com/nim
github.com/jaridmargolin/inspect-process
github.com/darcyclarke/rawkit
Additional Debugging APIs:
1. Debugging an existing Node process:
2. process._debugProcess(pid);
3.
4.
5. GDB-like CLI Debugger:
6. node inspect filename.js
7.
8. Drive with DevTools Protocol via WS port:

const dp = require('chrome-remote-interface');

async function test() {


const client = await dp();
const {Profiler, Runtime} = client;

await Profiler.enable();
await Profiler.setSamplingInterval({interval: 500});

await Profiler.start();
await Runtime.evaluate({expression: 'startTest();'});
await sleep(800);

const data = await Profiler.stop();


require('fs').writeFileSync('data.cpuprofile',
JSON.stringify(data.profile));
};

test().then((result)=>{
console.log(result);
})
.catch((error)=>{
console.log(error);
});

9. DevTools Protocol via require('inspector'):

const inspector = require('inspector');


const fs = require('fs');
const session = new inspector.Session();

session.connect();
session.post('Profiler.enable');
session.post('Profiler.start');

setTimeout( function() {
session.post('Profiler.stop',
function(err, data) {
fs.writeFileSync('data.cpuprofile',
JSON.stringify(data.profile));
});
}, 8000);
Another awesome thing in using Chrome as a debugging tool is that you can
debug both your front-end and back-end JavaScript code with the same
interface.

JSON: JavaScript Object Notation


JSON is a text format for storing and transporting data

JSON is "self-describing" and easy to understand

JSON Example
This example is a JSON string:

'{"name":"John", "age":30, "car":null}'

It defines an object with 3 properties:

• name
• age
• car

Each property has a value.

If you parse the JSON string with a JavaScript program, you can access the
data as an object:

let personName = obj.name;


let personAge = obj.age;

What is JSON?
• JSON stands for JavaScript Object Notation
• JSON is a lightweight data-interchange format
• JSON is plain text written in JavaScript object notation
• JSON is used to send data between computers
• JSON is language independent *

*
The JSON syntax is derived from JavaScript object notation, but the JSON
format is text only.

Code for reading and generating JSON exists in many programming


languages.
The JSON format was originally specified by Douglas Crockford.

Why Use JSON?


The JSON format is syntactically similar to the code for creating JavaScript
objects. Because of this, a JavaScript program can easily convert JSON data
into JavaScript objects.

Since the format is text only, JSON data can easily be sent between
computers, and used by any programming language.

JavaScript has a built in function for converting JSON strings into JavaScript
objects:

JSON.parse()

JavaScript also has a built in function for converting an object into a JSON
string:

JSON.stringify()

You can receive pure text from a server and use it as a JavaScript object.

You can send a JavaScript object to a server in pure text format.

You can work with data as JavaScript objects, with no complicated parsing
and translations.

Storing Data
When storing data, the data has to be a certain format, and regardless of
where you choose to store it, text is always one of the legal formats.

JSON makes it possible to store JavaScript objects as text.

The JSON syntax is a subset of the JavaScript syntax.

JSON Syntax Rules


JSON syntax is derived from JavaScript object notation syntax:
• Data is in name/value pairs
• Data is separated by commas
• Curly braces hold objects
• Square brackets hold arrays

JSON Data - A Name and a Value


JSON data is written as name/value pairs (aka key/value pairs).

A name/value pair consists of a field name (in double quotes), followed by a


colon, followed by a value:

Example
"name":"John"

JSON names require double quotes.

JSON - Evaluates to JavaScript Objects


The JSON format is almost identical to JavaScript objects.

In JSON, keys must be strings, written with double quotes:

JSON
{"name":"John"}

In JavaScript, keys can be strings, numbers, or identifier names:

JavaScript
{name:"John"}

JSON Values
In JSON, values must be one of the following data types:
• a string
• a number
• an object
• an array
• a boolean
• null

In JavaScript values can be all of the above, plus any other valid JavaScript
expression, including:

• a function
• a date
• undefined

In JSON, string values must be written with double quotes:

JSON
{"name":"John"}

In JavaScript, you can write string values with double or single quotes:

JavaScript
{name:'John'}

JavaScript Objects
Because JSON syntax is derived from JavaScript object notation, very little
extra software is needed to work with JSON within JavaScript.

With JavaScript you can create an object and assign data to it, like this:

Example
person = {name:"John", age:31, city:"New York"};

You can access a JavaScript object like this:

Example
// returns John
person.name;
It can also be accessed like this:

Example
// returns John
person["name"];

Data can be modified like this:

Example
person.name = "Gilbert";

It can also be modified like this:

Example
person["name"] = "Gilbert";

You will learn how to convert JavaScript objects into JSON later in this
tutorial.

JavaScript Arrays as JSON


The same way JavaScript objects can be written as JSON, JavaScript arrays
can also be written as JSON.

You will learn more about objects and arrays later in this tutorial.

JSON Files
• The file type for JSON files is ".json"
• The MIME type for JSON text is "application/json"

Both JSON and XML can be used to receive data from a web server.
The following JSON and XML examples both define an employees object, with
an array of 3 employees:

JSON Example
{"employees":[
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }
]}

XML Example
<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>

JSON is Like XML Because


• Both JSON and XML are "self describing" (human readable)
• Both JSON and XML are hierarchical (values within values)
• Both JSON and XML can be parsed and used by lots of programming
languages
• Both JSON and XML can be fetched with an XMLHttpRequest

JSON is Unlike XML Because


• JSON doesn't use end tag
• JSON is shorter
• JSON is quicker to read and write
• JSON can use arrays

The biggest difference is:

XML has to be parsed with an XML parser. JSON can be parsed by a


standard JavaScript function.

Why JSON is Better Than XML


XML is much more difficult to parse than JSON.
JSON is parsed into a ready-to-use JavaScript object.

For AJAX applications, JSON is faster and easier than XML:

Using XML

• Fetch an XML document


• Use the XML DOM to loop through the document
• Extract values and store in variables

Using JSON

• Fetch a JSON string


• JSON.Parse the JSON string

Valid Data Types


In JSON, values must be one of the following data types:

• a string
• a number
• an object (JSON object)
• an array
• a boolean
• null

JSON values cannot be one of the following data types:

• a function
• a date
• undefined
JSON Strings
Strings in JSON must be written in double quotes.

Example
{"name":"John"}

JSON Numbers
Numbers in JSON must be an integer or a floating point.

Example
{"age":30}

JSON Objects
Values in JSON can be objects.

Example
{
"employee":{"name":"John", "age":30, "city":"New York"}
}

Objects as values in JSON must follow the JSON syntax.

JSON Arrays
Values in JSON can be arrays.

Example
{
"employees":["John", "Anna", "Peter"]
}
JSON Booleans
Values in JSON can be true/false.

Example
{"sale":true}

JSON null
Values in JSON can be null.

Example
{"middlename":null}

JSON.parse()
A common use of JSON is to exchange data to/from a web server.

When receiving data from a web server, the data is always a string.

Parse the data with JSON.parse(), and the data becomes a JavaScript
object.

Example - Parsing JSON


Imagine we received this text from a web server:

'{"name":"John", "age":30, "city":"New York"}'

Use the JavaScript function JSON.parse() to convert text into a JavaScript


object:

const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');


Make sure the text is in JSON format, or else you will get a syntax error.

Use the JavaScript object in your page:

Example
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = obj.name;
</script>

Array as JSON
When using the JSON.parse() on a JSON derived from an array, the method
will return a JavaScript array, instead of a JavaScript object.

Example
const text = '["Ford", "BMW", "Audi", "Fiat"]';
const myArr = JSON.parse(text);

Exceptions
Parsing Dates
Date objects are not allowed in JSON.

If you need to include a date, write it as a string.

You can convert it back into a date object later:

Example
Convert a string into a date:

const text = '{"name":"John", "birth":"1986-12-14", "city":"New


York"}';
const obj = JSON.parse(text);
obj.birth = new Date(obj.birth);

document.getElementById("demo").innerHTML = obj.name + ", " +


obj.birth;
Or, you can use the second parameter, of the JSON.parse() function,
called reviver.

The reviver parameter is a function that checks each property, before


returning the value.

Example
Convert a string into a date, using the reviver function:

const text = '{"name":"John", "birth":"1986-12-14", "city":"New


York"}';
const obj = JSON.parse(text, function (key, value) {
if (key == "birth") {
return new Date(value);
} else {
return value;
}
});

document.getElementById("demo").innerHTML = obj.name + ", " +


obj.birth;

Parsing Functions
Functions are not allowed in JSON.

If you need to include a function, write it as a string.

You can convert it back into a function later:

Example
Convert a string into a function:

const text = '{"name":"John", "age":"function () {return 30;}",


"city":"New York"}';
const obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");

document.getElementById("demo").innerHTML = obj.name + ",


" + obj.age();
You should avoid using functions in JSON, the functions will lose their scope,
and you would have to use eval() to convert them back into functions.

JSON.stringify()
A common use of JSON is to exchange data to/from a web server.

When sending data to a web server, the data has to be a string.

Convert a JavaScript object into a string with JSON.stringify().

Stringify a JavaScript Object


Imagine we have this object in JavaScript:

const obj = {name: "John", age: 30, city: "New York"};

Use the JavaScript function JSON.stringify() to convert it into a string.

const myJSON = JSON.stringify(obj);

The result will be a string following the JSON notation.

myJSON is now a string, and ready to be sent to a server:

Example
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = JSON.stringify(obj);

You will learn how to send JSON to a server in the next chapters.

Stringify a JavaScript Array


It is also possible to stringify JavaScript arrays:

Imagine we have this array in JavaScript:


const arr = ["John", "Peter", "Sally", "Jane"];

Use the JavaScript function JSON.stringify() to convert it into a string.

const myJSON = JSON.stringify(arr);

The result will be a string following the JSON notation.

myJSON is now a string, and ready to be sent to a server:

Example
const arr = ["John", "Peter", "Sally", "Jane"];
const myJSON = JSON.stringify(arr);

You will learn how to send a JSON string to a server in the next chapters.

Storing Data
When storing data, the data has to be a certain format, and regardless of
where you choose to store it, text is always one of the legal formats.

JSON makes it possible to store JavaScript objects as text.

Example
Storing data in local storage

// Storing data:
const myObj = {name: "John", age: 31, city: "New York"};
const myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);

// Retrieving data:
let text = localStorage.getItem("testJSON");
let obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;

JSON Object Literals


This is a JSON string:

'{"name":"John", "age":30, "car":null}'


Inside the JSON string there is a JSON object literal:

{"name":"John", "age":30, "car":null}

JSON object literals are surrounded by curly braces {}.

JSON object literals contains key/value pairs.

Keys and values are separated by a colon.

Keys must be strings, and values must be a valid JSON data type:

• string
• number
• object
• array
• boolean
• null

Each key/value pair is separated by a comma.

It is a common mistake to call a JSON object literal "a JSON object".

JSON cannot be an object. JSON is a string format.

The data is only JSON when it is in a string format. When it is converted to a


JavaScript variable, it becomes a JavaScript object.

JavaScript Objects
You can create a JavaScript object from a JSON object literal:

Example
myObj = {"name":"John", "age":30, "car":null};

Normally, you create a JavaScript object by parsing a JSON string:

Example
myJSON = '{"name":"John", "age":30, "car":null}';
myObj = JSON.parse(myJSON);
Accessing Object Values
You can access object values by using dot (.) notation:

Example
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
x = myObj.name;

You can also access object values by using bracket ([]) notation:

Example
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
x = myObj["name"];

You might also like