Nodejs Material
Nodejs Material
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.
Node.js eliminates the waiting, and simply continues with the next request.
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
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.
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>_
Start your command line interface, write node myfirst.js and hit enter:
Initiate "myfirst.js":
If anyone tries to access your computer on port 8080, they will get a "Hello
World!" message in return!
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");
console.time("Getting data");
//
// Do some processing here...
//
console.timeEnd('Getting data');
console.info("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.
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
console.log("Program Ended");
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');
Example
Create a js file named main.js with the following code −
// Import events module
var events = require('events');
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.
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.
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);
1. node timer5.js
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. node timer2.js
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);
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.
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);
1. node timer3.js
Error Handlling
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.
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:
or
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) {}
You can add multiple handlers, that can catch different kinds of errors.
To solve this, you listen for the uncaughtException event on the process object:
You don't need to import the process core module for this, as it's automatically
injected.
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:
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))
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(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 −
• 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]);
Compare Buffers
Syntax
Following is the syntax of the method to compare two Node buffers −
buf.compare(otherBuffer);
Parameters
Here is the description of the parameters used −
• otherBuffer − This is the other buffer which will be compared with buf
Return Value
Returns a number indicating whether it comes before or after or is the same as the
otherBuffer in sort order.
Example
var buffer1 = new Buffer('ABC');
var buffer2 = new Buffer('ABCD');
var result = buffer1.compare(buffer2);
if(result < 0) {
console.log(buffer1 +" comes before " + buffer2);
} else if(result === 0) {
console.log(buffer1 +" is same as " + buffer2);
} else {
console.log(buffer1 +" comes after " + buffer2);
}
//copy a buffer
var buffer2 = new Buffer(3);
buffer1.copy(buffer2);
console.log("buffer2 content: " + buffer2.toString());
Slice Buffer
Syntax
Following is the syntax of the method to get a sub-buffer of a node buffer −
buf.slice([start][, end])
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());
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');
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
readerStream.on('end',function() {
console.log(data);
});
readerStream.on('error', function(err) {
console.log(err.stack);
});
console.log("Program Ended");
Writing to a Stream
Create a js file named main.js with the following code −
var fs = require("fs");
var data = 'Simply Easy Learning';
writerStream.on('error', function(err) {
console.log(err.stack);
});
console.log("Program Ended");
console.log("Program Ended");
console.log("File Compressed.");
console.log("File Decompressed.");
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");
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 −
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");
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");
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");
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);
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);
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);
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");
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");
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");
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");
fs.readdir("/tmp/",function(err, files) {
if (err) {
return console.error(err);
}
files.forEach( function (file) {
console.log( file );
});
});
});
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.
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>
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
4. Now, click on the Node.js icon. The terminal will show the following
message:
const dp = require('chrome-remote-interface');
await Profiler.enable();
await Profiler.setSamplingInterval({interval: 500});
await Profiler.start();
await Runtime.evaluate({expression: 'startTest();'});
await sleep(800);
test().then((result)=>{
console.log(result);
})
.catch((error)=>{
console.log(error);
});
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 Example
This example is a JSON string:
• name
• age
• car
If you parse the JSON string with a JavaScript program, you can access the
data as an object:
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.
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 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.
Example
"name":"John"
JSON
{"name":"John"}
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
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"};
Example
// returns John
person.name;
It can also be accessed like this:
Example
// returns John
person["name"];
Example
person.name = "Gilbert";
Example
person["name"] = "Gilbert";
You will learn how to convert JavaScript objects into JSON later in this
tutorial.
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>
Using XML
Using JSON
• a string
• a number
• an object (JSON object)
• an array
• a boolean
• null
• 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"}
}
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
<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.
Example
Convert a string into a date:
Example
Convert a string into a date, using the reviver function:
Parsing Functions
Functions are not allowed in JSON.
Example
Convert a string into a function:
JSON.stringify()
A common use of JSON is to exchange data to/from a web 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.
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.
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;
Keys must be strings, and values must be a valid JSON data type:
• string
• number
• object
• array
• boolean
• null
JavaScript Objects
You can create a JavaScript object from a JSON object literal:
Example
myObj = {"name":"John", "age":30, "car":null};
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"];