This Edureka "Node.js tutorial" will help you to learn the Node.js fundamentals and how to create an application in Node.js. Node.js is an open-source, cross-platform JavaScript runtime environment for developing a diverse variety of server tools and applications. Below are the topics covered in this tutorial:
1) Client Server Architecture
2) Limitations of Multi-Threaded Model
3) What is Node.js?
4) Features of Node.js
5) Node.js Installation
6) Blocking Vs. Non – Blocking I/O
7) Creating Node.js Program
8) Node.js Modules
9) Demo – Grocery List Web Application using Node.js
2. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Agenda
❖ Client Server Architecture
❖ Limitations of Multi–Threaded Model
❖ What is Node.js?
❖ Features of Node.js
❖ Node.js Installation
❖ Blocking Vs. Non – Blocking I/O
❖ Creating Node.js First Program
❖ Node.js Modules
❖ Demo – Grocery List Web Application using Node.js
5. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Traditional Multi-Threaded Model
Handle Request
A
Handle Request
B
Handle Request
C
Read ResponseRead Request
Assign Thread for A
Assign Thread for C
Assign Thread for B
Thread
Thread
Thread
User HTTP Request A
User HTTP Request B
User HTTP Request C
User HTTP Request D
7. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Limitations of Multi-Threaded Models
Shared
Resources
Updating
Resources
Wants to
Update
Wants to
Update
Thread A Thread C
Thread B
➢ In a multi-threaded HTTP server, for each and every request that the server receives, it creates a separate thread
which handles that request
➢ If a request acquires a lock in the shared resource and it is ‘exclusive’, it will affect result of other requests
8. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
High chances of deadlock if application
is not designed properly
Limitations of Multi-Threaded Models
Web Servers need to handle thousands
of HTTP requests. So, many threads may
have to wait for network operations
For thousands of simultaneous requests,
spawning threads for all processes would
not achieve the desired scalability
Scalability
Complex
Deadlock
10. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
What is Node.js?
➢Node.js is an open source runtime environment for server-side and networking applications and is single threaded.
➢Uses Google JavaScript V8 Engine to execute code.
➢It is cross platform environment and can run on OS X, Microsoft Windows, Linux, FreeBSD, NonStop and IBM.
➢Provides an event driven architecture and non blocking I/O that is optimized and scalable.
N O D E
12. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Features of Node.js
1. Asynchronous
Caller Recipient
request
response
callback
➢ When request is made to server, instead of waiting for the request to complete, server continues to
process other requests
➢ When request processing completes, the response is sent to caller using callback mechanism
Asynchronous Model
Asynchronous
Event Driven
Very Fast
Scalable
13. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Features of Node.js
➢ When request is made to server, instead of waiting for the request to complete, server continues to
process other requests
➢ When request processing completes, the response is sent to caller using callback mechanism
Event Emitters
Event Loop
(Single - threaded)
File System
Network
Process
Other
Event Queue
Thread Pool
2. Single Threaded and Event Driven:
Asynchronous
Event Driven
Very Fast
Scalable
14. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Features of Node.js
3. Very Fast
4. Single Threaded but Highly Scalable
Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code
execution.
Node.js is highly scalable because event mechanism helps the server to respond in a non-
blocking way.
Asynchronous
Event Driven
Very Fast
Scalable
16. EDUREKA NODE JS CERTIFICATION TRAINING www.edureka.co/mastering-node-js
Node.js Installation
Go to https://nodejs.org/en/1
Download and Install2
17. EDUREKA NODE JS CERTIFICATION TRAINING www.edureka.co/mastering-node-js
Node.js Installation
Open node.js command prompt3
➢ node –version
Check the version of Node.js
installed
19. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Node.js First Program
Create a Directory: mkdir node_example1
Create a File: first_example.js2
Go to the node_example directory3
Execute the java script file: node first_example.js4
2
1
3
4
21. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Simple Web Application Example
Example:
Importing Module:
‘require’ is used to load a Node.js modules.
1
Example:
Creating Server
➢ Used to create web server object
➢ Function (request, response) is called once for
every HTTP request to the server, so it's called
the request handler.
2
listen(<port_no>)
Bind the server instance for listening to a particular port.3
Example:
22. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Simple Web Application Example
1 Import HTTP Module
2 Define Port No.
3 Creating Server Instance
4 Sending HTTP Header
6
Binding Server Instance
with the Port No. 3000
5 Sending Data
25. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Blocking vs Non–Blocking I/O
➢ Blocking is when the execution of additional JavaScript in the Node.js process must wait until a non-JavaScript
operation completes.
➢ "I/O" refers primarily to interaction with the system's disk and network supported by libuv.
More methods will be blocked till
the read method is not executed
More method will execute
asynchronously
(non-blocking way)
27. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Blocking vs Non–Blocking I/O
Blocking Example:
C O N C L U S I O N :
➢ In case of Asynchronous (non-blocking ), once file I/O is complete, it will call the callback function
➢ This allows Node.js to be scalable and process large number of request without worrying about blocking I/O
29. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
NPM
➢ NPM stands for Node Package Manager
➢ Provides online repositories for node.js packages/modules
➢ Provides command line utility to install Node.js packages along with version management and dependency
management.
30. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
NPM
npm install Install all the modules as specified in package.json
npm install <Module Name> Install Module using npm
npm install <Module Name> -g Install dependency globally
32. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Global Objects
These objects are available in all modules and therefore, are referred as Global Objects
specifies the name of the directory that currently contains the code.
__dirname
specifies the name of the file that currently contains the code.
__filename
33. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Global Objects
A timer in Node.js is an internal construct that calls a given function after a certain period of time.
setTimeout(callback, delay[, ...args])
➢ Schedules execution of a one-time callback after delay milliseconds
➢ Returns a Timeout for use with clearTimeout( )
setInterval(callback, delay[, ...args])
➢ Schedules repeated execution of callback every delay milliseconds.
➢ Returns a Timeout for use with clearTimeout( )
setImmediate(callback, [,..args])
➢ Schedules an immediate execution of the callback after I/O events' callbacks but
before setTimeout() and setInterval() timers are triggered.
➢ Returns an Immediate for use with clearImmediate().
36. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
File System
File I/O is provided by simple wrappers around standard POSIX functions. For importing File
System Module (fs), we use: var fs = require("fs");
All methods have asynchronous and synchronous formsImportant Note:
FS Methods
Asynchronous
Forms
Synchronous
Forms
1
var fs = require("fs");
// Asynchronous read
fs.readFile(‘test.txt', function (err, data) { });
// Synchronous read
var data = fs.readFileSync('input.txt');
37. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
File System
The asynchronous form always takes a completion callback as its last argument.
var fs = require("fs");
// Asynchronous read
fs.readFile(‘test.txt’, function (err, data) {
if (err) {
return console.error(err);
}
console.log(data.toString());
});
FS Methods
Arg 1
Callback Method
(last argument)
Arg 2
Arg 3
Callback As Last Arg.
Important Note: 2
38. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
File System
First argument in completion callback is always reserved for an exceptionImportant Note: 3
Callback
Method
Arg 1: exception
Arg N
Arg 2
Arg 3
var fs = require("fs");
// Asynchronous read
fs.readFile(‘test.txt’, function (err, data) {
if (err) {
return console.error(err);
}
console.log(data.toString());
});
Reserved for
exception
returns null or undefined
(successful completion)
39. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Some Methods in File System Module – Open()
fs.open( path, flags[, mode], callback )
fs.openSync( path, flags[, mode] )
fs.close( fd, callback )
➢ var fs = require(‘fs’);
Open File Asynchronously
Open File Synchronously
Closing File
Arguments Description
Path < string > Path of the file
Flags < string > Access Modifiers
Mode < integer > sets the permission and sticky bits, but only if the file was created
Callback < function > Callback signature - function(err, fd)
40. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Flag Modes in Open Method
Modes Description
r Open file for reading. an exception occurs if the file does not exist
r+ Open file for reading and writing. Exception: if the file does not exist
w Open file for writing. The file is created ( if it does not exist) or truncated (if it exists)
wx Like 'w' but fails if path exists
w+ Open file for reading and writing. File is created (if it does not exist) or truncated (if it exists)
wx+ Same as 'w+' but fails if path exists
a Open file for appending. The file is created if it does not exist
ax Like 'a' but fails if path exists
a+ open file for reading and appending. the file is created if it does not exist.
ax+ Like 'a+' but fails if path exists
41. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Some Methods in File System Module – Read()
read(fd, buffer, offset, length, position, callback)
readFile(file[, options], callback)
readFileSync(file[, options])
Read Content of a File into Buffer
Reads File Asynchronously
Arguments Description
fd < integer > File Descriptor
buffer <string | Buffer | Unit8Array > The buffer that the data will be written to.
offset < integer > Offset in the buffer to start writing at.
length < integer > Specifies the number of bytes to read.
position < integer > Specifies where to begin reading from in the file
Callback < function > Read Callback signature - function(err, bytesRead, buffer)
Reads File Synchronously
42. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Some Methods in File System Module – Write()
writeFile(file, data[, options], callback)
writeFileSync(file, data[, options])
Writes into a File Asynchronously
Arguments Description
File Filename or File Descriptor
Data The buffer that the data will be written to.
Options: Encoding, Mode or flag
Callback < function > Callback signature - function(err, bytesRead, buffer)
Writes into a File Synchronously
44. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Some Methods in File System Module – Write()
Callback is an asynchronous equivalent for a function and is called at the completion of each task
Callback: will execute after
file read is complete
Output:
46. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Events
➢ Node.js follows event-driven architecture where certain objects (called "emitters") periodically emit
named events which further invokes the listeners (function).
➢ Node.js provide concurrency by using the concept of events and callbacks
➢ All objects that emit events are instances of the EventEmitter class.
var eventEmitter = event.EventEmitter();
Importing ‘events’ module
Object of EventEmitter Class
eventEmitter.emit(‘event’)
Registering listeners
Trigger event
eventEmitter.on(‘event’, eventHandler)
var event = require(‘events’);
47. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Events
Import Events Module
Creating object of EventEmitter
Emitting event
Registering Listener and defining
event handler
OUTPUT
49. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Web Application Architecture
Client Client Client Client
Mobile
Browser
Web
Browser
Application
Web Server
Application
Server
File System
Database
External
File System
Client Server Business Layer Data Layer
Makes HTTP Request
to the server
Serve the request
Made by client and
pass the response
contains application
utilized by web server to
do required processing.
Consists of Database
and other data storage
50. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
HTTP
Import Required Modules
Creating Server
Parse the fetched URL to get pathname
Request file to be read from file system
(index.html)
Creating Header with content type as text or HTML
Generating Response
Listening to port: 3000
53. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Express Framework
➢ Express is a minimal and flexible Node.js web application framework that provides a robust set of features for
web and mobile applications.
➢ Inspired by Sinatra (web framework based on Ruby) and also, intertwined with Connect, a “plugin” library for
Node.
➢ Express used to come bundled with Connect before version 4.0
➢ After version 4.0, Connect (and all middleware except static) was removed to allow these middleware to be
updated independently
55. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
RESTful API
REST stands for REpresentational State Transfer.
Used create a new resource
or update a existing
resource
1 POST
Used to provide a read
only access to a resource
2 GET
Used to create a update
a resource
3 PUT
Used to remove a resource
4 DELETE
C R U DCreate Delete
Read Update
57. www.edureka.co/mastering-node-jsEDUREKA NODE JS CERTIFICATION TRAINING
Popular Frameworks Around Node.js
E X P R E S S
Minimalistic Web
Framework based on
Node.js
S A I L S
Project generator,
Middleware and
Templating Engine
M E T E O R
Full Stack Framework
that covers server,
mobile, desktop & web
apps
K O A
Web Framework
designed by the team
behind Express
N O D E