UNIT-1 (Introduction To Full Stack Development)
UNIT-1 (Introduction To Full Stack Development)
•Front end
•Back end
•Data bases
FULL STACK DEVELOPMENT
•A web-application is an application program that is usually stored on a remote server, and
users can access it through the use of Software known as web-browser.
•It is a type of computer program that usually runs with the help of a web browser and also
uses many web technologies to perform various tasks on the internet.
•A web application can be developed for several uses, which can be used by anyone like it can
be used as an individual or as a whole organization for several reasons.
•The frontend is what users see and interact with, while the backend is how everything
works behind the scenes. Both sides need to work together seamlessly to ensure a functional
website.
1. Front End Development
•The frontend is the part of the website users directly interact with. This includes the design,
menus, text, images, videos, and overall layout.
•The main languages used for frontend development are HTML, CSS, and JavaScript.
Responsiveness and performance are the two main objectives of the Front End.
•The developer must ensure that the site is responsive i.e. it appears correc tly on devices of
all sizes no part of the website should behave abnormally irrespective of the size of the screen.
Front End Languages
∙ HTML: HTML stands for Hypertext Markup Language. It is used to design the front-end portion of
web pages using a markup language. HTML is a combination of Hypertext and Markup language.
Hypertext defines the link between web pages..
∙ CSS: Cascading Style Sheets fondly referred to as CSS is a simply designed language intended to
simplify the process of making web pages presentable. CSS allows you to apply styles to web pages.
∙ JavaScript: JavaScript is a famous scripting language used to create magic on sites to make the site
interactive for the user. It is used to enhance the functionality of a website to run cool games and
web-based software. Applicable in both front-end and back-end, Javascript is key to becoming a
good developer.
•There are many other languages through which one can do front-end development depending upon
the framework for example Flutter uses Dart, React uses JavaScript and Django uses Python…
Frontend Frameworks and Libraries:
∙ AngularJS: unit-4
∙ React.js: unit -5
∙ jQuery:
∙ SASS:
∙ Flutter:
2. Back End Development
• The backend is the server side of the website.
• Users don’t see or interact directly with the backend; it’s the behind-the-scenes functionality.
• The parts and characteristics developed by backend designers are indirectly accessed by
users through a front-end application.
• Activities, like writing APIs, creating libraries, and working with system components
without user interfaces or even systems of scientific programming, are also included in the
backend.
∙
Back End Languages
PHP: PHP is a server-side scripting language designed specifically for web development. Since PHP
code is executed on the server side, it is called a server-side scripting language.
∙ Java: Java is one of the most popular and widely used programming languages and platforms. It is
highly scalable.
∙ Python: Python is a programming language that lets you work quickly and integrate systems more
efficiently.
• Node.js: Node.js is an open-source and cross-platform runtime environment for executing JavaScript
code outside a browser. NodeJS is not a framework, and it’s not a programming language. We often
use Node.js for building back-end services like APIs like Web App or Mobile App.
Back-End Frameworks
∙ Express : unit-4
∙ Django
∙ Ruby on Rails
∙ Laravel
∙ Spring
∙ Some more back-end programming/scripting languages are C#, Ruby, GO, etc.
Understanding the Basic Web Development Framework
• The main components of any given web framework are the user, browser, webserver, and
backend services.
• Although websites vary greatly on appearance and behavior, all have these basic components in
one form or another.
• The components are described in a top-down manner from user down to backend services.
User
• Users are a fundamental part of all websites; User expectations define the
requirements for developing a good website, and these expectations have changed a
lot over the years.
• Users expect websites to behave closer to applications installed on their computers
and mobile devices.
• The user role in a web framework is to sit on the visual output and interaction input
of webpages.
• Users view the results of the web framework processing and then provide
interactions using mouse clicks, keyboard input, and swipes and taps on mobile
devices.
Browser
• The browser plays three roles in the web framework.
2. It interprets the data from the server and renders it into the view that the
user actually sees.
Webservers, such as Apache and IIS, are made to serve static files such as .html, .css, and
media files. To handle POST requests that modify server data and AJAX requests to interact
with backend services, webservers need to be extended with server-side scripts.
Server-side program & Backend Services
• A server-side program is really anything that can be executed by the webserver to perform the task the
browser is requesting. These can be written in PHP, Python, C, C++, C#, Java, …. Webservers such as
Apache and IIS provide mechanisms to include server-side scripts and then wire them up to specific URL
locations requested by the browser.
• The server-side scripts either generate the response directly by executing their code or connect with other
backend servers such as databases to obtain the necessary information and then use that information to build
and send the appropriate response.
• Backend Services
• Backend services are services that run behind the webserver and provide data used to build responses to
the browser.
• The most common type of backend service is a database that stores information.
• When a request comes in from the browser that requires information from the database or other backend
service, the server-side script connects to the database, retrieves the information, formats it, and then sends it
back to the browser. Conversely, when data comes in from a web request that needs to be stored in the
database, the server-side script connects to the database and updates the data.
Understanding the Node.js-to-Angular Stack Components
Figure 1.2 provides a basic diagram of how the Node.js-to-Angular stack fits into the basic
website/web application model.
Understanding the Node.js-to-Angular Stack Components
• The most common—and we believe the best—version of this stack is the Node.js-to-Angular
stack comprised of MongoDB, Express, Angular, and Node.js.
In the Node.js-to-Angular stack:
• Node.js provides the fundamental platform for development. The backend services and
server-side scripts are all written in Node.js.
• MongoDB provides the data store for the website but is accessed via a MongoDB driver
Node.js module.
• The webserver is defined by Express, which is also a Node.js module.
• The view in the browser is defined and controlled using the Angular framework or React.
• Angular is an MVC framework where the model is made up of JSON or JavaScript objects, the
view is HTML/ CSS, and the controller is made up of Angular JavaScript.
Browsers and Javascript engine
Node.js
• Node.js is a development framework based on Google’s V8 JavaScript engine.
Therefore, Node.js code is written in JavaScript and then compiled into machine code
by V8 to be executed.
• Many of your backend services can be written in Node.js, as can the server-side
scripts and any supporting web application functionality.
• The nice thing about Node.js is that it is all just JavaScript, so you can easily take
functionality from a client-side script and place it in a server-side script.
• Also, the webserver can run directly within the Node.js platform as a Node.js
module, so it makes it much easier than, say, Apache at wiring up new services or
server-side scripts.
Node.js
• The following are just a few reasons why Node.js is a great framework to start from:
JavaScript end-to-end: One of the biggest advantages to Node.js is that it allows you to write both
server- and client-side scripts in JavaScript. With Node.js you can take JavaScript written on
the client and easily adapt it for the server and vice versa.
Event-driven scalability: Node.js applies a different logic to handling web requests. Rather than
having multiple threads waiting to process web requests, they are processed on the same thread using
a basic event model. This allows Node.js webservers to scale in ways that traditional webservers never
can.
Extensibility: Node.js has a great following and an active development community. New modules
to extend Node.js functionality are being developed all the time. Also it is simple to install and include
new modules in Node.js, making it easy to extend a Node.js project to include new functionality in
minutes.
Time: Node.js is super easy to set up and develop in. In only a few minutes, you can install Node.js
and have a working webserver.
MongoDB
• MongoDB is an agile and scalable NoSQL (Not Only SQL) database.
• The name Mongo comes from “humongous.”
• It is based on the NoSQL document store model, meaning that data is stored in the
database as a form of JSON objects rather than the traditional columns and rows of a
relational database.
• MongoDB provides great website backend storage for high traffic websites that need to
store data such as user comments, blogs, or other items because it is fast, scalable, and easy
to implement.
• Node.js supports a variety of DB access drivers, so the data store could just as easily be
MySQL or some other database.
MongoDB
• However, the following are some of the reasons that MongoDB really fits in the Node.js stack well:
■ Document orientation: Because MongoDB is document-oriented, the data is stored in the
database in a format close to what you will be dealing with in both server-side and client- side
scripts. This eliminates the need to transfer data from rows to objects and back.
High performance: MongoDB is one of the highest performing databases available. Especially
today when more and more people interact with websites, it is important to have a backend that can
support heavy traffic.
High availability: MongoDB’s replication model makes it easy to maintain scalability while
keeping high performance.
High scalability: MongoDB’s structure makes it easy to scale horizontally by sharing the data
across multiple servers.
No SQL injection: MongoDB is not susceptible to SQL injection (putting SQL statements in web
forms or other input from the browser that compromises the DB security) because objects are
stored as objects, not using SQL strings.
Express
• The Express module acts as the webserver in the Node.js-to-Angular stack.
• The Express module extends Node.js to provide several key components for handling web
requests.
The following is a partial list of the valuable features of Express:
■ Route management: Express makes it easy to define routes (URL endpoints) that tie directly
to Node.js script functionality on the server.
■ Error handling: Express provides built-in error handling for documents not found and other
errors.
■ Easy integration: An Express server can easily be implemented behind an existing reverse proxy
system such as Nginx or Varnish. This allows it to be easily integrated into your existing secured
system.
■ Cookies: Express provides easy cookie management.
■ Session and cache management: Express also enables session management and cache
management.
Angular
• Angular is a client-side framework developed by Google.
• Angular provides all the functionality needed to handle user input in the browser, manipulate data on
the client side, and control how elements are displayed in the browser view.
• It is written using TypeScript.
• Angular provides a framework that makes it easy to implement web applications using the MVC framework.
• Benefits of Angular:
■ Data binding: Angular has a clean method to bind data to HTML elements using its powerful scope
mechanism.
■ Extensibility: The Angular architecture allows you to easily extend almost every aspect of the language to
provide your own custom implementations.
■ Clean: Angular forces you to write clean, logical code.
■ Reusable code: The combination of extensibility and clean code makes it easy to write reusable code in
Angular. Support: Google is investing a lot into this project, which gives it an advantage over other similar
initiatives.
■ Compatibility: Angular is based on TypeScript, which makes it easier to begin integrating Angular into your
environment and to reuse pieces of your existing code within the structure of the Angular framework
ReactJS
• ReactJS, also known as React, is a popular JavaScript library for building user interfaces.
• It is also referred to as a front-end JavaScript library.
• It was developed by Facebook and is widely used for creating dynamic and interactive web applications.
• React is a declarative, component based library that allows developers to build reusable UI components and It
follows the Virtual DOM (Document Object Model) approach, which optimizes rendering performance by
minimizing DOM updates.
Features of React:
1. Component-Based Architecture
2. JSX (JavaScript Syntax Extension)
3. Virtual DOM
4. One-way Data Binding
5. Performance
6. Components
7. Single-Page Applications (SPAs)
JavaScript Primer(basics)
Each component of Node.js, Express, TypeScript, and Angular is based on the JavaScript
language. This makes it easy to implement and reuse code at all levels of your web development
stack. we need to familiarize you with some of the language basics of JavaScript, such as variables,
functions, and objects.
• Defining Variables
• Variables are a means to name data so that you can use that name to temporarily store and access
data from your JavaScript files.
• Variables can point to simple data types such as numbers or strings, or they can point to more
complex data types such as objects.
•To define a variable in JavaScript you use the var keyword and then give the variable a name, for
example:
• var myData;
• You can also assign a value to the variable in the same line.
• var myString = "Some Text";
JavaScript Primer(basics)
• The following lines work as well:
• var myString;
• myString = "Some Text";
• Once you have declared the variable, you can use the name to assign the variable a value and
access the value of the variable:
• var myString = "Some Text";
• var newString = myString + " Some More Text";
• Your variable names should describe the data stored in them so that it is easy to use them later in
your program.
• The only rules for creating variable names is that they must begin with a letter, $, or _, and they
cannot contain spaces. Also remember that variable names are case sensitive, so using myString is
different from MyString.
Understanding JavaScript Data Types
•JavaScript has 8 Datatypes
•String
•Number
•Bigint
•Boolean
•Undefined
•Null
•Symbol
•Object
Understanding JavaScript Data Types
• JavaScript uses data types to determine how to handle data assigned to a variable. The variable type
determines what operations you can perform on the variable, such as looping or executing.
■ String: Stores character data as a string. The character data is specified by either single or double
quotes. All the data contained in the quotes will be assigned to the string variable. For example:
• var myString = 'Some Text';
• var anotherString = 'Some More Text';
■ Number: Stores the data as a numerical value. Numbers are useful in counting, calculations,
and comparisons. Some examples are
• var myInteger = 1;
• var cost = 1.33;
■ Boolean: Stores a single bit that is either true or false. Booleans are often used for flags. The
following examples define a true and a false variable.
• var yes = true;
• var no = false;
Understanding JavaScript Data Types
■ Array: An indexed array is a series of separate distinct data items all stored under a single variable
name. Items in the array can be accessed by their zero-based index using array[index].
• var arr = ["one", "two", "three"] ;
• var first = arr[0];
•Object literal:
JavaScript supports the ability to create and use object literals. When you use an object literal you
can access values and functions in the object using the object.property syntax.
• var obj = {"name": "Brendan", "Hobbies":["Video Games", "camping"], "age”:22};
• var name = obj.name;
•
■ Null: At times you do not have a value to store in a variable either because it hasn’t been created
or you are no longer using it. At this time you can set a variable to null.
• var newVar = null;
Java Script Operators :
• Assignment operators
• Comparison operators
• Arithmetic operators
• Bitwise operators
• Logical operators
• BigInt operators
• String operators
• Conditional (ternary) operator
• Comma operator
• Unary operators
• Relational operators
Using if Statements
•An if statement allows you to separate code execution based on the evaluation of a
comparison. In the following lines of code the conditional operators are in (), and the code to
execute if the conditional evaluates to true is in {}:
if(x==5){ do_something();
}
• In addition to only executing code within the if statement block, you can specify an else
• block that gets executed only if the condition is false. For example:
if(x==5){ do_something();
} else { do_something_else();
}
•You can also chain if statements together. To do this add a conditional statement along with an
else statement, for example:
if(x<5){ do_something();
} else if(x<10) { do_something_else();
} else { do_nothing();
Implementing switch Statements
•The switch statement allows you to evaluate an expression once and then, based on the
value, execute one of many different sections of code.
• The syntax for the switch statement is
switch(expression){
case value1:
<code to execute>
break;
case value2:
<code to execute>
break;
default:
<code to execute if not value1 or value2>
}
Implementing Looping
• while Loops
• The most basic type of looping in JavaScript is the while loop. A while loop tests an expression and
continues to execute the code contained in its {} brackets until the expression evaluates to false.
while (i<5){
console.log("Iteration " + i + "<br>"); i++;
}
• do/while Loops
•Another type of while loop is the do/while loop. This is useful if you always want to execute the code
in the loop at least once and the expression cannot be tested until the code has executed at least once.
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
var i=0;
do{
var day=days[i++];
console.log("It's " + day + "<br>");
} while (day != "Wednesday");
for Loops
• The JavaScript for loop allows you to execute code a specific number of times by using a for
statement that combines three statements into a single block of execution using the following
syntax:
for (assignment; condition; update;){
code to be executed;
}
• The for statement uses those three statements as follows when executing the loop:
■ assignment: Executed before the loop begins and not again. This is used to initialize
variables that will be used in the loop as conditionals.
■ condition: Expression evaluated before each iteration of the loop. If the expression evaluates
to true the loop is executed; otherwise, the for loop execution ends.
■ update: Executed each iteration after the code in the loop has executed. This is typically used
to increment a counter that is used in statement 2.
Creating Functions
Syntax for Function Declaration:
function functionName(x, y) { statements... return (z) };
let z = x - y;
return z;
Applications of Node.js :
Web applications
Internet of Things systems
APIs
Real-time chats
Complex single-page applications
Real-time collaboration tools
Streaming apps
What Is Node.js Used For?
• Node.js can be used for a wide variety of purposes. Because it is based on V8 and
has highly optimized code to handle HTTP traffic, the most common use is as a
webserver. However, Node.js can also be used for a variety of other web services
such as:
■ Web services APIs such as REST
■ Real-time multiplayer games
■ Backend web services such as cross-domain, server-side requests
■ Web-based applications
■ Multiclient communication such as IM
What Does Node.js Come With?
• Node.js comes with many built-in modules available right out of the box.
■ Assertion testing: Allows you to test functionality within your code.
■ Buffer: Enables interaction with TCP streams and file system operations.
■ C/C++ add-ons: Allows for C or C++ code to be used just like any other Node.js module.
■ Child processes: Allows you to create child processes.
■ Cluster: Enables the use of multicore systems.
■ Command line options: Gives you Node.js commands to use from a terminal.
■ Console: Gives the user a debugging console.
■Crypto: Allows for the creation of custom encryption.
■ Debugger: Allows debugging of a Node.js file.
■ DNS: Allows connections to DNS servers.
■ Errors: Allows for the handling of errors.
■ Events: Enables the handling of asynchronous events.
■ File system: Allows for file I/O with both synchronous and asynchronous methods
■ Globals: Makes frequently used modules available without having to include them first.
■ HTTPS: Enables HTTP over the TLS/SSL.
What Does Node.js Come With?
■ HTTP: Enables support for many HTTP features.
■ OS: Allows access to the operating system that Node.js is running on.
■ Path: Enables access to file and directory paths.
■ Process: Provides information and allows control over the current Node.js process.
■ Query strings: Allows for parsing and formatting URL queries.
■ Readline: Enables an interface to read from a data stream.
■ REPL: Allows developers to create a command shell.
■ Stream: Provides an API to build objects with the stream interface.
■ String decoder: Provides an API to decode buffer objects into strings.
■ Timers: Allows for scheduling functions to be called in the future.
■ TLS/SSL: Implements TLS and SSL protocols.
■ URL: Enables URL resolution and parsing.
■ Utilities: Provides support for various apps and modules.
■ V8: Exposes APIs for the Node.js version of V8.
■ VM: Allows for a V8 virtual machine to run and compile code.
■ ZLIB: Enables compression using Gzip and Deflate/Inflate.
Installing Node.js
• To easily install Node.js, download an installer from the Node.js website at http://nodejs.org.
The Node.js installer installs the necessary files on your PC to get Node.js up and running. No
additional configuration is necessary to start creating Node.js applications.
• Looking at the Node.js Install Location
• If you look at the install location, you will see a couple of executable files and a node_modules
folder. The node executable file starts the Node.js JavaScript VM. The following list describes
the executables in the Node.js install location that you need to get started:
■ node: This file starts a Node.js JavaScript VM. If you pass in a JavaScript file location, Node.js
executes that script. If no target JavaScript file is specified, then a script prompt is shown that
allows you to execute JavaScript code directly from the console.
■ npm: This command is used to manage the Node.js packages discussed in the next section.
■ node_modules: This folder contains the installed Node.js packages. These packages act as
libraries that extend the capabilities of Node.js.
Verify Node.js Executables
• . To do so, open a console prompt and execute the following command to bring up a Node.js VM:
node
• Next, at the Node.js prompt execute the following to write "Hello World" to the screen.
• >console.log("Hello World");
• You should see "Hello World" output to the console screen. Now exit the console using Ctrl+C in
Windows.
•Next, verify that the npm command is working by executing the following command in the OS console
prompt:
• npm version
You should see output similar to the following:
{ npm: '3.10.5',
ares: '1.10.1-DEV',
http_parser: '2.7.0',
icu: '57.1',
modules: '48',
node: '6.5.0',
openssl: '1.0.2h',
uv: '1.9.1',
v8: '5.1.281.81',
Selecting a Node.js IDE
Integrated Development Environment (IDE):
• Most developers are particular about the IDE that they like to use, and there will likely be a
way to configure at least for JavaScript if not Node.js directly. For example, Eclipse has
some great Node.js plugins, and the WebStorm IDE by IntelliJ has some good features for
Node.js built in.
• we use Visual Studio Code for the built-in TypeScript functionality required later in this
book.
• you can use any editor you want to generate your Node.js web applications. In reality, all you
need is a decent text editor.
• Almost all the code you will generate will be .js, json, .html, and .css.
• So pick the editor in which you feel the most comfortable writing those types of files.
Working with Node Packages
• One of the most powerful features of the Node.js framework is the ability to easily extend it with additional
Node Packaged Modules (NPMs) using the Node Package Manager (NPM).
• That’s right, in the Node.js world, NPM stands for two things. This book refers to the Node Packaged Modules
as modules to make it easier to follow.
}).listen(3000);
• To run the file open a terminal on your editor and type the
following command
• node index.js
• The console of the text editor must show the message ‘Server
running on port 3000’
• To check if the server is actually running or not, navigate to your
browser, and on the address bar/URL bar type the below line and
hit enter.
• localhost:3000
Using Events, Listeners, Timers, and Callbacks in Node.js
• Understanding the Node.js Event Model
• Node.js applications are run in a single-threaded event-driven model. Although Node.js implements a thread
pool in the background to do work, the application itself doesn’t have any concept of multiple threads.
• Comparing Event Callbacks and Threaded Models
• In the traditional threaded web model, a request comes in to the webserver and is assigned to an available
thread. Then the handling of work for that request continues on that thread until the request is complete and
a response is sent.
• Figure 4.1 illustrates the threaded model processing two requests, GetFile and GetData. The GetFile
request first opens the file, reads the contents, and then sends the data back in a response. All this occurs in
order on the same thread.
The GetData request connects to the DB
, queries the necessary data, and then
sends the data in the response.
Comparing Event Callbacks and Threaded Models
• Instead of executing all the work for each request on individual threads, work is
added to an event queue and then picked up by a single thread running an event loop.
• The event loop grabs the top item in the event queue, executes it, and then grabs the
next item.
• When executing code that is no longer live or has blocking I/O, instead of calling the
function directly, the function is added to the event queue along with a callback that is
executed after the function completes.
• When all events on the Node.js event queue have been executed, the Node application
terminates.
Comparing Event Callbacks and Threaded Models
Figure 4.2 illustrates the way Node.js handles the GetFile and GetData requests.
The GetFile and GetData requests are added to the event queue. Node.js first picks up the GetFile
request, executes it, and then completes by adding the Open() callback function to the event queue.
Next, it picks up the GetData request, executes it, and completes by adding the Connect() callback
function to the event queue.
This continues until there are no callback functions to be executed.
Notice in Figure 4.2 that the events for each thread do not necessarily follow a direct interleaved order.
For example, the Connect request takes longer to complete than the Read request, so Send(file) is
called before Query(db)
Node.js event model
Events in Node.js
In Node.js applications, Events and Callbacks concepts are used to provide concurrency. As
Node.js applications are single threaded and every API of Node js are asynchronous. So it uses
async function to maintain the concurrency. Node uses observer pattern. Node thread keeps an
event loop and after the completion of any task, it fires the corresponding event which signals
the event listener function to get executed.
Event Driven Programming
Node.js uses event driven programming. It means as soon as Node starts its server, it simply
initiates its variables, declares functions and then simply waits for event to occur. It is the one
of the reason why Node.js is pretty fast compared to other similar technologies.
There is a main loop in the event driven application that listens for events, and then triggers a
callback function when one of those events is detected.
Events in Node.js
Although, Events and Callbacks look similar but the differences lies in the fact that callback
functions are called when an asynchronous function returns its result where as event
handling works on the observer pattern.
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 is used to bind events and event listeners.
Events in Node.js
// Importing events
const EventEmitter = require('events');
// Initializing event emitter instances
var eventEmitter = new EventEmitter();
// Registering to myEvent
eventEmitter.on('myEvent', (msg) => {
console.log(msg);
});
// Triggering myEvent
eventEmitter.emit('myEvent', "First event");
// Triggering myEvent
eventEmitter.emit('myEvent', "Second event");
console.log("program ended...")
Output:
First event
Second event
program ended...
Events in Node.js
var events = require('events'); // Import events module
var eventEmitter = new events.EventEmitter(); // Create an eventEmitter object
// Create an event handler as follows
var connectHandler = function connected() {
console.log('connection succesful.');
eventEmitter.emit('data_received'); // Fire the data_received event
}
eventEmitter.on('connection', connectHandler); // Bind the connection event with the handler
// Bind the data_received event with the anonymous function
eventEmitter.on('data_received', function(){
console.log('data received succesfully.');
});
eventEmitter.emit('connection'); // Fire the connection event
console.log("Program Ended.");
Output:
connection succesful.
data received succesfully.
Program Ended.
Adding Work to the Event Queue
• In Node.js applications, work is scheduled on the event queue by passing a callback
function using one of these methods:
• Make a call to one of the blocking I/O library calls such as writing to a file or
connecting to a database.
• Add a built-in event listener to a built-in event such as an http.request or
server. connection.
• Create your own event emitters and add custom listeners to them.
• Use the process.nextTick option to schedule work to be picked up on the next
cycle of the event loop.
• Use timers to schedule work to be done after a particular amount of time or at
periodic intervals.
Implementing Timers
•A useful feature of Node.js and JavaScript is the ability to delay execution of code for a period of
time. There are three types of timers in Node.js: timeout, interval, and immediate.
•Delaying Work with Timeouts
•Timeout timers are used to delay work for a specific amount of time. When that time expires, the
callback function is executed and the timer goes away. Use timeouts for work that only needs to be
performed once.
•Timeout timers are created using the setTimeout(callback, delayMilliSeconds, [args]) method built
into Node.js.
•When you call setTimeout(), the callback function is executed after delayMilliSeconds expires.
•For example, the following executes myFunc() after 1 second:
•setTimeout(myFunc, 1000);
•The setTimeout() function returns a timer object ID. You can pass this ID to clearTimeout(timeoutId)
at any time before the delayMilliSeconds expires to cancel the timeout function.
•For example:
Delaying Work with Timeouts
• The syntax of implementing callback in Node.js is as follows −
• function function_name(argument, function (callback_argument){
// callback body
})
• The setTimeout() function in Node.js is a typical example of callback. The following code calls the
asynchronous setTimeout() method, which waits for 1000 milliseconds, but doesn't block the thread.
Instead, the subsequent Hello World message, followed by the timed message.
• ---------------------------------------------------------------
setTimeout(function () {
console.log('This prints after 1000 ms');
}, 1000);
console.log("Hello World");
• -------------------------------------------------------------------
• -Output
• Hello World
• This prints after 1000 ms
Performing Periodic Work with intervals
• Interval timers are used to perform work on a regular delayed interval. When the delay time expires, the
callback function is executed and is then rescheduled for the delay interval again. Use intervals for work that
needs to be performed on a regular basis.
• Interval timers are created using the setInterval(callback, delayMilliSeconds, [args])
method built into Node.js. When you call setInterval(), the callback function is executed every interval
after delayMilliSeconds has expired. For example, the following executes myFunc() every second:
• setInterval(myFunc, 1000);
• The setInterval() function returns a timer object ID.
• You can pass this ID to clearInterval(intervalId) at any time before the delayMilliSeconds
expires to cancel the timeout function.
• For example:
• myInterval = setInterval(myFunc, 100000);
• … clearInterval(myInterval);
Performing Periodic Work with intervals
Implementing Callbacks
• A Callback in Node.js is an asynchronous equivalent for a function. It is a special type of
function passed as an argument to another function. Node.js makes heavy use of callbacks.
Callbacks help us make asynchronous calls. All the APIs of Node are written in such a way
that they support callbacks.
• Programming instructions are executed synchronously by default. If one of the instructions in a
program is expected to perform a lengthy process, the main thread of execution gets blocked.
The subsequent instructions can be executed only after the current I/O is complete. This is
where callbacks come in to the picture.
• The callback is called when the function that contains the callback as an argument completes
its execution, and allows the code in the callback to run in the meantime. This makes Node.js
highly scalable, as it can process a high number of requests without waiting for any function to
return results.
• The syntax of implementing callback in Node.js is as follows −
• function function_name(argument, function (callback_argument){
// callback body
})
Implementing Callbacks
// call back function
var fs= require('fs')
fs.writeFile('file.txt','call back functions',function()
{
console.log(" data written to file.txt")
})
console.log('End of the program.....’)
Output:
End of the program.....
data written to file.txt
Implementing Callbacks
• The setTimeout() function in Node.js is a typical example of callback. The
following code calls the asynchronous setTimeout() method, which waits for
1000 milliseconds, but doesn't block the thread. Instead, the subsequent Hello
World message, followed by the timed message.
• ---------------------------------------------------------------
setTimeout(function () {
console.log('This prints after 1000 ms');
}, 1000);
console.log("Hello World");
• -------------------------------------------------------------------
• -Output
• Hello World
• This prints after 1000 ms