NodeJS CDAC Mar22
NodeJS CDAC Mar22
JS
Server Side Javascript
Node.js – an intro
• In 2009 Ryan Dahl created Node.js or Node, a framework primarily used to create highly
scalable servers for web applications.
Node.js is an open source, cross-platform runtime environment for server-side JavaScript.
Node.js is required to run JavaScript without a browser support. It uses Google V8 JavaScript engine to
execute code.
It is written in C++ and JavaScript.
Node.js is a development framework that is based on Google’s V8 JavaScript engine that powers
Google's Chrome web browser.
You write Node.js code in JavaScript, and then V8 compiles it into machine code to be executed.
It’s a highly scalable system that uses asynchronous, non-blocking I/O model (input/output), rather than
threads or separate processes
It is not a framework like jQuery nor a programming language like C# or JAVA; Its primarily a Javascript
engine
• This style of programming — whereby instead of using a return value you define functions
that are called by the system when interesting events occur — is called event-driven or
asynchronous programming.
Typical blocking I/O
programming
result = query('SELECT * FROM posts WHERE id = 1');
do_something_with(result);
query_finished = function(result) {
do_something_with(result);
}
query('SELECT * FROM posts WHERE id = 1', query_finished);
Event loop
• An event loop is a construct that mainly performs two functions in a continuous loop —
event detection and event handler triggering.
In any run of the loop, it has to detect which events just happened.
Then, when an event happens, the event loop must determine the event callback and invoke it.
• This event loop is just one thread running inside one process, which means that, when
an event happens, the event handler can run without interruption. This means the
following:
There is at most one event handler running at any given time.
Any event handler will run to completion without being interrupted.
Node.js uses the “Single Threaded Event Loop” architecture to handle multiple concurrent clients.
Asynchronous and Event Driven
• All APIs of Node.js library are asynchronous that is, non-blocking.
It essentially means a Node.js based server never waits for an API to return data.
The server moves to the next API after calling it and a notification mechanism of Node.js helps
the server to get a response from the previous API call.
It is non-blocking, so it doesn't make the program wait, but instead it registers a callback and lets
the program continue.
• Node.js is not fit for an application which performs CPU-intensive operations like image
processing or other heavy computation work because it takes time to process a request
and thereby blocks the single thread.
• Node.js is great for data-intensive applications.
Using a single thread means that Node.js has an extremely low-memory footprint when used as
a web server and can potentially serve a lot more requests.
Eg, a data intensive application that serves a dataset from a database to clients via HTTP
//helloworld.js
console.log("Hello World!");
Using the REPL
• To view the options available to you in REPL type .help and press Enter.
Node js Modules
• A module in Node.js is a logical encapsulation of code in a single unit.
Since each module is an independent entity with its own encapsulated functionality, it can be managed
as a separate unit of work.
• Node.js has a set of built-in modules which you can use without any further installation.
Built-in modules provide a core set of features we can build upon.
Also, each module can be placed in a separate .js file under a separate folder.
To include a module, use the require() function with the name of the module.
res.end(body);
}
exports object is a special object created by the Node module system which is returned as the value of
the require function when you include that module.
Create Your Own Modules
• Exports is just module.exports’s little helper. Your module returns module.exports to the caller ultimately,
not exports. All exports does is collect properties and attach them to module.exports
//module7.js //import the assigned properties with a destructuring assignment:
function sayHello(){ const { username, sayHello } = require(‘./module7’)
console.log("Hello World!")
} //Or with a regular assignment and dot notation:
//alternatively
exports.username = username
exports.sayHello = sayHello
• There are two ways to install a package using npm: globally and locally.
• Globally − This method is generally used to install development tools and CLI based
packages. To install a package globally, use the following code.
npm install -g <package-name>
Eg to install expressJS : npm install -g express
Eg to install Typescript : npm install –g typescript
Eg to install Angular : npm install -g @angular/cli
• Locally − This method is generally used to install frameworks and libraries. A locally
installed package can be used only within the directory it is installed.
To install a package locally, use the same command as above without the -g flag.
npm install <package-name>
Eg : To install cookie parser in Express : npm install --save cookie-parser
Eg: to install bootstrap : npm install [email protected]
NPM (Node Package Manager)
• When packages are installed, they are saved on local machine
• npm installs module packages to the node_modules folder.
• Installing a package using NPM : $ npm install [g] <Package Unique Name>
• To remove an installed package : npm uninstall [g] < Package Unique Name>
• To update a package to its latest version : npm update [g] < Package Unique Name>
Loading a third party module : package.json
• The package.json file in Node.js is the heart of the entire application.
It is basically the manifest file that contains the metadata of the project.
package.json is a configuration file from where the npm can recognize dependencies between packages
and installs modules accordingly.
It must be located in project’s root directory.
It contains human-readable metadata about the project (like the project name and description) as well as
functional metadata like the package version number and a list of dependencies required by the
application.
Your project also must include a package.json before any packages can be installed from NPM.
Eg : a minimal package.json:
{
"name" : "barebones",
"version" : "0.0.0",
}
o The name field should explain itself: this is the name of your project. The version field is used by npm to make sure
the right version of the package is being installed.
Loading a third party module
• Lets say I want to create a ExpressJS application. I will install ExpressJs locally.
Step-1) choose a empty folder
Step-2) run npm init to create a package.json file
Step-3) install express : npm install express –save (to update package.json)
Step-4) check the updated json file to see new dependencies
See how package.json is installed in root folder along with node_modules folder
My Express app is dependent on a number of other modules
All these dependencies will have an entry in package.json
Loading a file module
• Loading a file module (User defined module)
We load non-core modules by providing the absolute path / relative path.
Node will automatically add the .js extension to the module referred.
var myModule = require(‘d:/shrilata/nodejs/module'); // Absolute path for module.js
var myModule = require('../module'); // Relative path for module.js (one folder up level)
var myModule = require('./module'); // Relative path for module.js (Exists in current directory)
If the given path does not exist, require() will throw an Error with its code property set to
'MODULE_NOT_FOUND'.
package.json
• The package.json file in Node.js is the heart of the entire application.
• It is basically the manifest file that contains the metadata of the project.
• package.json is a configuration file from where the npm can recognize dependencies
between packages and installs modules accordingly.
It must be located in project’s root directory.
• package-lock.json file
Introduced in version 5; keeps track of the exact version of every package that is installed so that
a product is 100% reproducible in the same way even if packages are updated by their
maintainers.
The package-lock.json sets your currently installed version of each package in stone, and npm
will use those exact versions when running npm install.
Buffers
• A buffer is an area of memory; It represents a fixed-size chunk of memory (can't be resized)
allocated outside of the V8 JavaScript engine.
You can think of a buffer like an array of integers, which each represent a byte of data.
It is implemented by the Node.js Buffer class.
• Creating Buffer
It is possible to create your own buffer! Aside from the one Node.js will automatically create during a
stream, it is possible to create and manipulate your own buffer
A buffer is created using the : Buffer.alloc(), Buffer.allocUnsafe() , Buffer.from()
Eg : Create a buffer of length 20, with initializing all the value to fill as 0 in hexadecimal format
Node.js fs (File System) Module
• The fs module provides a lot of very useful functionality to access and interact with the file
system.
There is no need to install it. Being part of the Node.js core, it can be used by simply requiring it:
const fs = require('fs')
• This module provides a wrapper for the standard file I/O operations.
• All the methods in this module has asynchronous and synchronous forms.
synchronous methods in this module ends with 'Sync'. For instance renameSync() is the synchronous
method for rename() synchronous method.
The asynchronous form always take a completion callback as its last argument.
The arguments passed to the completion callback depend on the method, but the first argument is
always reserved for an exception. If the operation was completed successfully, then the first argument
will be null or undefined.
When using the synchronous form any exceptions are immediately thrown. You can use try/catch to
handle exceptions or allow them to bubble up.
Asynchronous method is preferred over synchronous method because it never blocks the program
execution where as the synchronous method blocks.
Node.js File System
• Node fs module provides an API to interact with FileSystem and to perform some IO
operations like create a file, read a File, delete a File etc..
fs module is responsible for all the async or synchronous file I/O operations.
Node.js File System
• fs.readFile(fileName [,options], callback) : read the physical file asynchronously.
• fs.writeFile(filename, data [, options], callback) : writes data to a file
• fs.appendFile(): appends the content to an existing file
• fs.unlink(path, callback); delete an existing file
var fs = require("fs")
fs.unlink("test1.txt", function(err){
if(err) console.log("Err : " , err);
console.log("delete successful")
})
var fs = require("fs");
var path = "/";
fs.exists(path, function(exists) {
if (exists)
console.log(path + " exists: " + exists);
else
console.error("Something is wrong!");
});
• Reading Directories
We can use the fs.readdir() method to list all the files const fs = require('fs')
and directories within a specified path: fs.readdir('./', (err, files) => {
if (err) {
console.error(err)
return
}
console.log('files: ', files)
})
Node.js File System
• fs.open(path, flags[, mode], callback) : opens a file for reading or writing in async
path - string having file name including path.
flags - tells the behavior of the file to be opened
mode - sets the file mode; defaults to 0666, readable and writeable.
callback - function which gets two arguments (err, fd).
• fs.write(fd, string[, position[, encoding]], callback): write into an opened file; specified by fd
• Alternatively :fs.write(fd, buffer[, offset[, length[, position]]], callback)
var s = http.createServer(process_request);
s.listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Web development with Node : http.ServerRequest
• When listening for request events, the callback gets an http.ServerRequest object as the
first argument (function(req,res))
• This object contains some properties:
req.url: This property contains the requested URL as a string
o It does not contain the schema, hostname, or port, but it contains everything after that.
o Eg : if URL is :http://localhost:3000/about?a=20 then req.url will return /about?a=20
req.method: This contains the HTTP method used on the request. It can be, for example, GET,
POST, DELETE, or HEAD.
req.headers: This contains an object with a property for every HTTP header on the request.
Eg : Serving file on request : Reading a file at server end and serving to browser!
Serving file on request <!-- summer.html -->
<html>
<head>
<title>Hello there</title>
var http = require('http');
</head>
var url = require('url');
<body>
var fs = require('fs');
<h3>Welcome to Node!
Its summer now</h3>
http.createServer(function (req, res) {
</body>
var q = url.parse(req.url, true);
./summer.html </html>
var filename = "." + q.pathname;
Example promise.then(
function(result) { /* handle a successful result */ },
function(error) { /* handle an error */ }
);
promise.then(function(result) {
console.log("Promise worked");
}, function(err) {
console.log("Something broke");
});
Consuming a Promise
Full example
setTimeout(
() => number > expected
? resolve(number)
: reject(new Error('lower than expected number')), 1000
);
});
}
randomDelayed(100, 75, 2500)
.then(number => console.log(number))
.catch(error => console.error(error.toString()));
Chained Promises
• The methods promise.then(), promise.catch(), and promise.finally() can be used to associate
further action with a promise that becomes settled.
Each .then() returns a newly generated promise object, which can optionally be used for chaining
function load(url) {
return new Promise(function (resolve, reject) {
const request = new XMLHttpRequest();
request.onreadystatechange = function (e) {
if (this.readyState === 4) {
if (this.status == 200) {
resolve(this.response);
} else {
reject(this.status);
btn.onclick = function () {
}
load('data.json')
}
.then(
}
response => {
request.open('GET', url, true);
const result = JSON.parse(response);
request.send();
$(“#msg”).text(result.message);
});
},
}
error => $(“#msg”).text(`Error getting message,
HTTP status: ${error}`
);
}
Using Fetch
• One of the most useful and frequently used Web APIs that returns a promise is the
Fetch API.
It allows you to make an asynchronous resource request over a network.
fetch() is a two-part process, and therefore requires chaining then()
//complete example
async function hello(){
return "hello-1"
}
hello().then((x)=>console.log(x))
// returns"hello-1"
f().then(function(result) {
console.log(result)
});
The await keyword
• The await keyword is used inside the async function to wait for the asynchronous operation
await can be put in front of any async promise-based function to pause your code on that line until the
promise fulfills, then return the resulting value.
Syntax: let result = await promise;
You can use await when calling any function that returns a Promise, including web API functions
// a promise
let promise = new Promise(function (resolve, reject) { function logFetch(url) {
setTimeout(function () { return fetch(url)
resolve('Promise resolved')}, 4000); .then(response => response.text())
}); .then(text => {
console.log(text);
}).catch(err => {
async function asyncFunc() {// async function console.error('fetch failed', err);
});
// wait until the promise resolves }
let result = await promise;
async function logFetch(url) {
console.log(result); try {
console.log('hello'); const response = await fetch(url);
} console.log(await response.text());
}
asyncFunc(); // calling the async function catch (err) {
console.log('fetch failed', err);
}
}
Next gen Javascript
• const : from JS 1.5 onwards.- to define constants
Eg :
const myBirthday = '18.04.1982';
myBirthday = '01.01.2001'; // error, can't reassign the constant!
constructor method is
always defined with
the name "constructor"
console.log(square.calcArea()); // 100
Next gen Javascript : Spread and rest operators
• spread:
// Destructuring assignment
var {x, y, width, height} = rect;
console.log(x, y, width, height); // 0,10,15,20
rect.x = 10;
const arr=[1,2,3,4,5]
var [a,b] = arr
console.log(a,b) //1,2
Array functions
• Array.filter
You can filter arrays by using the .filter(callback) method.
The result will be another array that contains 0 or more elements based on the condition (or the
"check") that you have in the callback.
• With a template, we can create one string and insert the variable values by surrounding
them with ${variable}.
console.log(`${lastName}, ${firstName} ${middleName}`)
Any JavaScript that returns a value can be added to a template string between the ${ } in a
template string.
//Javascript : generating an html string
var msg1 = 'Have a great day';
var html = '<div>' + msg1 + '</div>';
document.write(html)
• Responsive web design is about creating web sites which automatically adjust themselves
to look good on all devices, from small phones to large desktops.
Developers can then create a single design that works on any kind of device: mobiles, tablets, smart
TVs, and PCs
Where to Get Bootstrap 4?
• There are two ways to start using Bootstrap 4 on your own web site.
Download Bootstrap 4 from getbootstrap.com : https://getbootstrap.com/docs/4.5/getting-
started/download/
If you don't want to download and host Bootstrap 4 yourself, you can include it from a CDN (Content
Delivery Network).
MaxCDN provides CDN support for Bootstrap's CSS and JavaScript. You must also include jQuery
The https://getbootstrap.com/docs/4.5/getting-started/introduction/ page gives CDN links for CSS and
js files
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap 4 Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js">
</script>
</head>
<body>
//body comes here
</body>
</html>
To ensure proper rendering and touch zooming, add this <meta> tag
• The width=device-width part sets the width of the page to follow the
screen-width of the device (which will vary depending on the device).
• The initial-scale=1 part sets the initial zoom level when the page is first
loaded by the browser.
Create First Web Page With Bootstrap 4
• Bootstrap 4 also requires a containing element to wrap site contents.
• There are two container classes to choose from:
The .container class provides a responsive fixed width container
The .container-fluid class provides a full width container, spanning the entire width of the
viewport
Bootstrap Container
• Bootstrap container is basically used in order to create a centered area that lies within the
page and generally deals with the margin of the content and the behaviors that are
responsible for the layout.
It contains the grid system (row elements, which in turn are the container of columns).
• There are two container classes in Bootstrap:
.container: provides a fixed width container with responsiveness. It will not take the complete width of
its viewport.
.container-fluid: provides a full width container of the viewport and its width will change (expand or
shrink) on different screen sizes.
<body>
<div class="container">
<h1>Container</h1>
</div>
</body>
Bootstrap Grid System
• Bootstrap grid system divides the screen into columns―up to 12 in each row. (rows are
infinite)
The column widths vary according to the size of screen they're displayed in.
Bootstrap's grid system is responsive, as the columns resize themselves dynamically when the
size of browser window changes.
If you do not want to use all 12 columns individually, you can group the columns together to
create wider columns
it is a good practice to wrap all the contents within a container; create a row (with class row)
inside a container, then start creating the columns.
<div class="container">
<div class="row">
//add desired number of cols here
</div>
</div>
Grid Classes
• The Bootstrap 4 grid system has five classes:
.col- (extra small devices - screen width less than 576px)
.col-sm- (small devices - screen width equal to or greater than 576px)
.col-md- (medium devices - screen width equal to or greater than 768px)
.col-lg- (large devices - screen width equal to or greater than 992px)
.col-xl- (xlarge devices - screen width equal to or greater than 1200px)
Example
Building a Basic Grid
MISC COMPONENTS
<h1> - <h6>
• Typography refers to the various styles present in Bootstrap style sheets which define how
various text elements will appear on the web page.
HTML uses default font and style to create headings, paragraphs, lists and other inline elements.
Bootstrap overrides default and provides consistent styling across browsers for common typographic
elements.
• Bootstrap 4 styles HTML headings (<h1> to <h6>) with a bolder font-weight and an increased
font-size
• Additionally, you can use the <small> tag with .text-muted class to display the secondary text
of any heading in a smaller and lighter variation.
Working with Paragraphs
• Bootstrap's global default font-size is 1rem (typically 16px), with a line-height of 1.5. This is
applied to the <body> and all paragraphs
You can also make a paragraph stand out by adding the class .lead on it.
You can also transform the text to lowercase, uppercase or make them capitalize.
• Text Coloring
Colors are the powerful method of conveying important information in website design.
Tables
• Bootstrap provides an efficient layout to build elegant tables
You can create tables with basic styling that has horizontal dividers and small cell padding, by just adding
the Bootstrap's class .table to the <table> element.
<div class="jumbotron">
<h1>Bootstrap Tutorial</h1>
<p>Bootstrap is the most popular HTML, CSS, and JS framework for
developing responsive, mobile-first projects on the web.</p>
</div>
images
• To add images on the webpage use element <img> , it has three classes to apply
simple styles to images.
.img-rounded : To add rounded corners around the edges of the image, radius of the border is
6px.
.img-circle : To create a circle of radius is 500px
.img-thumbnail : To add some padding with grey border , making the image look like a polaroid
photo.
• If you want to create a horizontal menu using ordered or unordered list you need to place all
list items in a single line i.e. side by side.
You can do this by simply applying the class .list-inline to the respective <ul> or <ol>, and the class .list-
inline-item to the <li> elements.
Page Components : List Group
• List group is used for creating lists; eg a list of useful resources or a list of recent activities
Add class list-group to a <ul> or <div> element to make its children appear as a list.
The children can be li or a element, depending on your parent element choice.
The child should always have the class list-group-item.
Page Components : List Group
• We can display a number beside each list item using the badge component.
Add this inside each “list-group-item” to display badge; badges align to the right of each list item
• We can also apply various colors to each list item by adding list-group-item-*
classes along with list-group-item.
Bootstrap 4 Navs
• Navs : a group of links placed inline with each other to be used for navigation.
There are options to make this group of links appear either as tabs or small buttons, the latter known
as pills in Bootstrap.
If you want to create a simple horizontal menu, add the .nav class to a <ul> element, followed by
.nav-item for each <li> and add the .nav-link class to their links:
Add the class .nav-tabs to the basic nav to generate a tabbed navigation.
Similarly, you can create pill based navigation by adding the class .nav-pills on the basic nav instead
of class .nav-tabs
Vertically stack these pills by attaching an additional class flex-column
Toggleable / Dynamic Pills
• To make the tabs toggleable, add the data-toggle="tab" attribute to each link.
Then add a .tab-pane class with a unique ID for every tab and wrap them inside a <div> element with
class .tab-content.
You can also create outline buttons by replacing the button modifier classes
<form class="form">
<div class="form-group">
<label for=“n1">Name</label>
<input type="text" class="form-control" id=“n1“ placeholder="Your Name" />
</div>
</form>
class form-control in an
input element will make it a
full-width element
Creating Forms : Vertical Form Layout
This is the default Bootstrap form layout in which styles are applied to form controls without adding any
base class to the <form> element or any large changes in the markup.
The form controls in this layout are stacked with left-aligned labels on the top.
Creating Forms : Horizontal Form Layout
Labels and form controls are aligned side-by-side using the Bootstrap grid classes.
To create this layout add the class .row on form groups and use the .col-*-* grid classes to specify the
width of your labels and controls.
Creating Forms : Inline Form Layout
• Additional rule for an inline form: Add class .form-inline to the <form> element