Web Technology with Node js, Angular js and MySQL
ISBN 9788119221653

Highlights

Notes

  

Module 1: Node js

Practical 1(a): Installation of Node js

Node.js development environment can be setup in Windows, Mac, Linux and Solaris. The following tools are required for developing a Node.js application on any platform.

    1. Node.js

    2. Node Package Manager (NPM)

    3. IDE (Integrated Development Environment) or TextEditor

NPM (Node Package Manager) is included in Node.js installation since Node version 0.6.0., so there is no need to install it separately.

Step 1 - Install Node.js on Windows

Visit Node js official website is https://nodejs.org/en/

It will automatically detect OS and display download link as per your Operating System. For example, it will display following download link for 64 bit Windows OS.

Download Node.JS Installer for Windows

Download node MSI for windows by clicking on 18.15.0 LTS or 19.8.1 Current button.

After you download the MSI, double-click on it to start the installation as shown below.

Node.js Installation

Click Next to read and accept the License Agreement and then click Install. It will install Node.js quickly on your computer. Finally, click finish to complete the installation.

Step 2 - Verify Installation

Once you install Node.js on your computer, you can verify it by opening the command prompt and typing node -v. If Node.js is installed successfully then it will display the version of the Node.js installed on your machine, as shown below.

Install Node.js on Mac/Linux

Visit Node.js official web site https://nodejs.org/en/download page. Click on the appropriate installer for Mac (.pkg or .tar.gz) or Linux to download the Node.js installer.

Node

Environment Setup

Once downloaded, click on the installer to start the Node.js installation wizard. Click on Continue and follow the steps. After successful installation, it will display summary of installation about the location where it installed Node.js and NPM.

Node.js Installation on OS X

After installation, verify the Node.js installation using terminal window and enter the following command. It will display the version number of Node.js installed on your Mac.

$ node -v

Optionally, for Mac or Linux users, you can directly install Node.js from the command line using Homebrew package manager for Mac OS or Linuxbrew package manager for Linux Operating System. For Linux, you will need to install additional dependencies, viz. Ruby version 1.8.6 or higher and GCC version 4.2 or higher before installing node.

$ brew install node

Practical 1(b): Installation of IDE or Texteditor

IDE

Node.js application uses JavaScript to develop an application. So, you can use any IDE or texteditor tool that supports JavaScript syntax. However, an IDE that supports auto complete features for Node.js API is recommended e.g. Visual Studio code, Visual Studio, Sublime text, Eclipse, Aptana etc.

Here, showing Visual Studio code installation

Step 1 – Visit the official website of the Visual Studio Code using any web browser like Google Chrome, Microsoft Edge, etc.

https://code.visualstudio.com/Download

Step 2 – Click on Download for windows

Step 3: Click on the installer icon to start the installation process of the Visual Studio Code.

Step 4: After the Installer opens, it will ask you for accepting the terms and conditions of the Visual Studio Code. Click on I accept the agreement and then click the Next button.

Step 5: Choose the location data for running the Visual Studio Code. It will then ask you for browsing the location. Then click on Next button.

Step 6: Then it will ask for beginning the installing setup. Click on the Install button.

Step 7: After clicking on Install, it will take about 1 minute to install the Visual Studio Code on your device.

Step 8: After the Installation setup for Visual Studio Code is finished, it will show a window like this below. Tick the “Launch Visual Studio Code” checkbox and then click Next.

Step 9: After the previous step, the Visual Studio Code window opens successfully. Now you can create a new file in the Visual Studio Code window and choose a language of yours to begin your programming journey!

So this is the way of installing Visual Studio Code on Windows system.

Practical 2: Working with REPL in Node js

Understanding REPL (Read Eval Print Loop) / node JS console. Or node shell.

Description: REPL stands for Read Eval Print Loop. It is a quick and easy way to test simple Node.js/Javascript code. The Node.JS Read Eval Print Loop (REPL) is an interactive shell that process Node.js expressions. The shell reads Javascript code the user enter, evaluates the result of interpreting the line of code, prints the result of the user, and loops until the user signals to quit.

The following table lists important REPL commands.

table-wrap

REPL Command

Description

.help

Display help on all the commands

tab Keys

Display the list of all commands.

Up/Down Keys

See previous commands applied in REPL.

.save filename

Save current Node REPL session to a file.

.load filename

Load the specified file in the current Node REPL session.

ctrl + c

Terminate the current command.

ctrl + c (twice)

Exit from the REPL.

ctrl + d

Exit from the REPL.

.break

Exit from multiline expression.

.clear

Exit from multiline expression.

To work the REPL (Node shell), follow the steps which are given below.

Step 1 - open command prompt (in Windows) or terminal (in Mac or UNIX/Linux)

Step 2 - Type node as shown below. It will change the prompt to > in Windows and MAC.

Examples in REPL

Ex. 1 Console

>console.log(“Hello World”);

>console.log(“Welcome to the node js session”);

Output:

Ex.2 Function

>function addition(x,y)

…{

…return x+y;

…}

>addition(12,50);

>function square(x)

…{

…return x*x

…}

>square(5);

>function area(x)

…{

…return 3.14*x*x

…}

>area(4);

>function cube(x)

…{

…return x*x*x

…}

>cube(3);

Output:

Ex.3 Variable

>10

>20

>x=10

>y=20

>x+y

>var x=10

>var y=70

>x+y

Output:

Ex.4 Javascript function

>function myfunction(n1,n2)

…{

…console.log(n1+n2)

…}

>myfunction(8,5);

>function mysub(n1,n2)

…{

…console.log(n1-n2)

…}

>mysub(20,10);

>function mydiv(n1,n2)

…{

…console.log(n1/n2)

…}

>mydiv(35,5);

>function mymulti(n1,n2)

…{

…console.log(n1*n2)

…}

>mymulti(5,4);

Output:

Practical 3: Node js Modules

Node.js modules are useful to move the common functionalities to separate .js file to reuse it in applications based on our requirements.

Each module has its own context, so if we create any new module that won’t interfere with other modules in application.

Type of Modules in Node Js

    1. Core (Built-in) Modules

    2. Local (Custom) Modules

    3. Third Party (External) Modules

Practical 3 (a) Create an application to demonstrate Node.js Built in Modules

List of some core modules in node. Js

table-wrap

Module

Description

assert

Provides a set of assertion tests

buffer

To handle binary data

child_process

To run a child process

cluster

To split a single Node process into multiple processes

crypto

To handle OpenSSL cryptographic functions

dgram

Provides implementation of UDP datagram sockets

dns

To do DNS lookups and name resolution functions

domain

Deprecated. To handle unhandled errors

events

To handle events

fs

To handle the file system

http

To make Node.js act as an HTTP server

https

To make Node.js act as an HTTPS server.

net

To create servers and clients

os

Provides information about the operation system

path

To handle file paths

punycode

Deprecated. A character encoding scheme

querystring

To handle URL query strings

readline

To handle readable streams one line at the time

stream

To handle streaming data

string_decoder

To decode buffer objects into strings

timers

To execute a function after a given number of milliseconds

tls

To implement TLS and SSL protocols

tty

Provides classes used by a text terminal

url

To parse URL strings

util

To access utility functions

v8

To access information about V8 (the JavaScript engine)

vm

To compile JavaScript code in a virtual machine

zlib

To compress or decompress files

Ex 1 os module

Syntax

The syntax for including the OS module in your application:

var os = require(‘os’);

OS Properties and Methods

table-wrap

Method

Description

arch()

Returns the operating system CPU architecture

constants

Returns an object containing the operating system’s constants for process signals, error cotes etc.

cpus()

Returns an array containing information about the computer’s CPUs

endianness()

Returns the endianness of the CPU

EOL

Returns the end-of-line marker for the current operating system

freemem()

Returns the number of free memory of the system

hostname()

Returns the hostname of the operating system

loadavg()

Returns an array containing the load averages, (1, 5, and 15 minutes)

networkInterfaces()

Returns the network interfaces that has a network address

platform()

Returns information about the operating system’s platform

release()

Returns information about the operating system’s release

tmpdir()

Returns the operating system’s default directory for temporary files

totalmem()

Returns the number of total memory of the system

type()

Returns the name of the operating system

uptime()

Returns the uptime of the operating system, in seconds

userInfo()

Returns information about the current user

Code

var os = require (‘os’);

console.log(os.EOL);

console.log(os.arch());

console.log(os.hostname());

console.log(os.totalmem());

console.log(os.freemem());

console.log(os.platform());

console.log(os.type());

console.log(os.userInfo());

output

PS C:\WebTechnologies\practical\OsModule> node osmodule.js

x64

DESKTOP-5LMD8KE

4209967104

1002143744

win32

Windows_NT

{

uid: -1,

gid: -1,

username: ‘Admin’,

homedir: ‘C:\\Users\\Admin’,

shell: null

}

Ex 2 path module

Code

// understanding path module in node js

var path = require (‘path’);

console.log(path.dirname(‘C:/avantika/practical/OsModule/demo.js’));//return directory name

console.log(path.basename(‘C:/avantika/practical/OsModule/demo.js’));//return file name

console.log(path.extname(‘C:/avantika/practical/OsModule/demo.js’));//return extension name

console.log(path.parse(‘C:/avantika/practical/OsModule/demo.js’))

const mypath = (path.parse(‘C:/avantika/practical/OsModule/demo.js’));

console.log(mypath.name);

console.log(mypath.root);

console.log(mypath.ext);

Output

PS C:\avantika\practical\OsModule> node demo.js

C:/avantika/practical/OsModule

demo.js

.js

{

root: ‘C:/’,

dir: ‘C:/avantika/practical/OsModule’,

base: ‘demo.js’,

ext: ‘.js’,

name: ‘demo’

}

demo

C:/

.js

PS C:\avantika\practical\OsModule>

Ex 3 url module

Code

//understanding url module in node js

var url = require (‘url’);

var adr = ‘https://www.google.com/search?client=firefox-b-d&q=url+module+in+node+js’;

var q= url.parse(adr, true);

console.log(q.host); //return www.google.com

console.log(q.pathname); //return /search

console.log(q.search); // return?client=firefox-b-d&q=url+module+in+node+js’

output

PS C:\avantika\practical\OsModule> node demo.js

www.google.com

/search

?client=firefox-b-d&q=url+module+in+node+js

PS C:\avantika\practical\OsModule>

Practical 3 (b) Create an application to demonstrate Node.js Local Modules

Step 1 create file calc.js and write following code

exports.add=function(x,y) {

return x+y;

};

exports.sub=function(x,y) {

return x-y;

};

exports.div=function(x,y) {

return x/y;

};

Step 2 – create file index.js and write following code

var calculator= require (‘./calc.js’);

var x= 50;

var y = 5;

console.log(“additon of x and y is “,calculator.add(x,y));

console.log(“subtraction of x and y is “,calculator.sub(x,y));

console.log(“multiplication of x and y is “,calculator.mul(x,y));

console.log(“division of x and y is “,calculator.div(x,y));

step 3 – run the file on terminal by writing node index .js
step 4 output

Practical 3 (c) Create an application to demonstrate Node.js Third Party Modules

Node Package Manager - NPM

NPM is the Package Manager for Node.js packages/modules

Install NPM:

NPM is installed by default when you install Node.js

Benefits of NPM:

    1. It Provides and hosts Online repositories for node.js packages/modules which can be easily downloaded and used in our projects. You can find them here: npmjs.com

    2. It Provides the Command-line utility in order to install various Node.js packages, manage Node.js versions and dependencies of the packages.

NPM useful commands:

Check NPM Version

npm -v

Install Packages via NPM

    1. Installed packages goes inside node_modules folder.

    2. In Short you can use - npm i <package_name>

    3. You can check out npm packages - npmjs.com

    4. In Latest version, --save is optional. it automatically save the package as a dependency in package.json

Syntax:

npm install <package_name>

Install the package globally

npm install <package_name> -g

Save the package as dependency

npm install <package_name> --save

Save the package as dev-dependency

npm install <package_name> --save-dev

Install the latest version of a package

npm install <package_name>@latest

Install any particluar version of a package

npm install <package_name>@<version_number>

//npm install express@4.11.1

Uninstalling Packages/Modules via NPM

npm uninstall <package_name>

Update Packages/Modules via NPM

npm update <package_name>

//aliases: up, upgrade

List all Installed Packages

npm ls

package.json

{

“name”: “MyNodeProject”,

“version”: “1.0.0”,

“description”: “My Nodejs Project”,

“main”: “app.js”,

“author”: {

“name”: “Dev”,

“email”: “dev@xyz.com”

},

“dependencies”: {

“body-parser”: “~1.10.2”,

“express”: “~4.11.1”,

“nodemon”: “^1.14.12”

},

“devDependencies”: {

“grunt”: “^0.4.5”,

“grunt-contrib-jshint”: “^0.10.0”,

“jshint-stylish”: “^0.2.0”,

“time-grunt”: “^0.3.2”

}

}

Node Version Manager - NVM

NVM stands for Node Version Manager, You can use nvm to change your node.js versions very easily this is very helpful if you are working on multiple projects of Node.js having different versions, etc.

Benefits of NVM:

    1. Easy to downloaded and use in your projects. You can find them here: NVM Github Link

    2. It Provides the Command-line utility in order to manage different Node.js versions on the same system/machine.

Install NPM:

Use the following command to install NVM on your machine

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/install.sh | bash

OR

wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/install.sh | bash

Some useful commands of NVM:

Check NVM Version

nvm --version

Check all Node.js versions installed on your machine

nvm ls

Check Node.js versions available to downloaded

nvm ls--remote

Install a particular version of Node.js

nvm install NODE_VERSION_NAME

//Replace NODE_VERSION_NAME to actual node.js version

Use a particular version of Node.js

nvm use NODE_VERSION_NAME

//Replace NODE_VERSION_NAME to actual node.js version

Set default version of Node.js

nvm alias default NODE_VERSION_NAME

//Replace NODE_VERSION_NAME to actual node.js version

Create new alias of Node.js

nvm alias ALIAS_NAME NODE_VERSION_NAME

//Replace

//NODE_VERSION_NAME to actual node.js version

//ALIAS_NAME to actual alias name

App.js

const express= require (‘express’);

const app= express();// initializing my express module

app.get(‘/’, function (req,res){

res.send(‘hello everyone for offline lectures’);

})

app.listen(3000, function(req,res){

console.log(“server is running on console”);

});

Practical 4: Node js Events

How node js works? OR (Event driven architecture/Event driven programming)

Event in node js

First understand the Callback Concept in node js

A function in NodeJS is either synchronous or asynchronous.

An asynchronous function is a function which has the functionality to call events when they complete the execution. The asynchronous function does not wait for any task to complete, it continues its execution with next instruction.

Callback function is a function which is called automatically after the completion of the execution of a time-intensive process.

We can understand it by one example - reading a text file using NodeJS.

Here, we assume that the text file is big so the process of reading this file is time-consuming. So, if we are to take a normal synchronous function for reading this text file, how it works is shown in the below example.

    1) Create one text file name – myfile.txt

    2) Create one js file to read the contents of file

    3) Run the file

Practical 4(a)

Myfile.txt

this is my file

which will have huge amount of data

and it will take time to read.

Sync.js

var fs = require(‘fs’);

console.log(‘here we started’);

console.log(‘--------------------------------’);

var contents = fs.readFileSync(‘myfile.txt’);

console.log(contents.toString());

console.log(‘--------------------------------’);

console.log(‘here we done’);

node sync.js

Practical 4(b)

reading file with asynchronous way

async.js

var fs= require(‘fs’);

console.log(‘here we started.....’);

var contents= fs.readFile(‘myfile.txt’,function(err, data){

if(err) throw err;

console.log(data.toString());

});

console.log(‘here we done .....................’);

node async.js

Methods in Events

emit(event, [arg1], [arg2], [arg3],….[]): emit() is used to raise an event. The first argument event is the name of the event.

on(event, listener): on() listens to the event and executes the event handler. The listener is the event handler.

once(event, listener): once() adds a one time listener.

addListener(event, listener): addListener() adds a listener to the end of listeners array for the specified event.

removeListener(event, listener): removeListener() removes a listener from the listener’s array for the specified event.

removeAllListeners([event]): removeAllListeners() removes all the listeners of the specified events.

listeners(event): listeners() returns an array of the specified event.

setMaxListeners(n): If more than 10 listeners are added to the event, the EventEmitter class gives a warning by default. This function allows the number of listeners to increase, in order.

The following table lists all the important methods of EventEmitter class.

table-wrap

EventEmitter Methods

Description

emitter.addListener(event, listener)

Adds a listener to the end of the listeners array for the specified event. No checks are made to see if the listener has already been added.

emitter.on(event, listener)

Adds a listener to the end of the listeners array for the specified event. No checks are made to see if the listener has already been added. It can also be called as an alias of emitter.addListener()

emitter.once(event, listener)

Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed.

emitter.removeListener(event, listener)

Removes a listener from the listener array for the specified event. Caution: changes array indices in the listener array behind the listener.

emitter.removeAllListeners([event])

Removes all listeners, or those of the specified event.

emitter.setMaxListeners(n)

By default EventEmitters will print a warning if more than 10 listeners are added for a particular event.

emitter.getMaxListeners()

Returns the current maximum listener value for the emitter which is either set by emitter.setMaxListeners(n) or defaults to EventEmitter.defaultMaxListeners.

emitter.listeners(event)

Returns a copy of the array of listeners for the specified event.

emitter.emit(event[, arg1][, arg2][, ...])

Raise the specified events with the supplied arguments.

emitter.listenerCount(type)

Returns the number of listeners listening to the type of event.

Events in NodeJS are same as a callback. A callback function is called when a function execution is completed where the events have to be fired based on the observer.

Every event has listeners and when an event is fired its related listener function starts the execution.

Below is some syntax for generating and firing events.

    1. For creating a new event var event=require(‘events’); var eventEmitter=new event.EventEmitter();

    2. For assigning any function to events. So, when this event is fired, the function gets executed. eventEmitter.on(‘eventName’,functionName);

    3. For firing the events. eventEmitter.emit(‘eventName’);

Practical 4(c) on the above information

var events= require(‘events’);

var emitter = new events.EventEmitter();

// listening to event

emitter.on(‘eventname’, () => {

console.log(‘event get fired’);

});

//event fired

emitter.emit(‘eventname’);

OR

const EventEmitter = require(‘events’);

var events= require(‘events’);

var emitter = new EventEmitter();

// listening to event

emitter.on(‘eventname’, () => {

console.log(‘event get fired’);

});

//event fired

emitter.emit(‘eventname’);

----------------------

Practical 4(d) emit with arguments

const EventEmitter = require(‘events’);

const events = require(‘events’);

const emitter = new EventEmitter();

emitter.on(‘saved’, (arg) => {

console.log(`A saved event occurred: number1: ${arg.n1}, number2: ${arg.n2}`);

});

emitter.emit(‘saved’, {

n1:‘10’,

n2: ‘20’

});

Practical 4(e)Myevent.js

//step 1- creating new event

var event= require(‘events’);

var myeventemitter= new event.EventEmitter();

//step 2 creating one function, this function get executed when event is fired.

//myeventemitter.on(‘eventName’,functionName);

myeventemitter.on(‘addition’, function(n1,n2) {

console.log(‘sum of two numbers’,n1+n2);

});

myeventemitter.on(‘multiplication’, function(n1,n2){

console.log(‘multiplication of two numbers’,n1*n2);

});

// step 3 For firing the events.

//myeventemitter.emit(‘eventName’);

myeventemitter.emit(‘addition’, 10,20);

myeventemitter.emit(‘multiplication’,8,9);

console.log(“done!!!!!!!”);

-------------------------------------------------------------------------------------------------------------

Practical 4(f) anotherway.js

// import events module

var events =require (‘events’);

// creating an event emitter object

var myeventemitter = new events.EventEmitter();

// write a function for event1

function listener1(){

console.log(‘event received by listener 1’);

}

// write a function for event2

function listener2(){

console.log(‘event received by listener 2’);

}

// adding listener throgh addListener or on

myeventemitter.addListener(‘write’,listener1);

myeventemitter.on(‘write’, listener2);

//emitting event

myeventemitter.emit(‘write’);

more event function

moreevent.js

var events = require(‘events’);

var eventEmitter = new events.EventEmitter();

// listener #1

var listner1 = function listner1() {

console.log(‘listner1 executed.’);

}

// listener #2

var listner2 = function listner2() {

console.log(‘listner2 executed.’);

}

// Bind the connection event with the listner1 function

eventEmitter.addListener(‘connection’, listner1);

// Bind the connection event with the listner2 function

eventEmitter.on(‘connection’, listner2);

var eventListeners = require(‘events’).EventEmitter.listenerCount

(eventEmitter,‘connection’);

console.log(eventListeners + “ Listner(s) listening to connection event”);

// Fire the connection event

eventEmitter.emit(‘connection’);

// Remove the binding of listner1 function

eventEmitter.removeListener(‘connection’, listner1);

console.log(“Listner1 will not listen now.”);

// Fire the connection event

eventEmitter.emit(‘connection’);

eventListeners = require(‘events’).EventEmitter.listenerCount(eventEmitter,’connection’);

console.log(eventListeners + “ Listner(s) listening to connection event”);

console.log(“Program Ended.”);

Practical 5: Node js Functions

A function is a parametric block of code defined once and called multiple times later. A function is a set of statements that is invoked in an application to perform a certain action or yield a desired result based on the login in the code. It is a open source javascript runtime environment.

Practical 5(a)

Code:

//simple addition function in node js var add=function(a,b){

return a+b;

}

console.log(‘Addition: ‘+add(10,20));

Output:

Practical 5(b)

Code:

//simple addition function in node js with arrow function var add=(a,b)=> a+b;

console.log(‘Addition: ‘+add(10,20));

Output:

Practical 5(c)

Code:

let myname={firstname: ‘rohit’, lastname: ‘lathigra’

};

(function(){

console.log(myname.firstname, myname.lastname);

})(myname);

Output:

Practical 5(d)

Code:

//anonymous function let show=function(){

console.log(‘show is anonymous function’)

};

show();

Output:

Practical 5(e)

Code:

//using anonymous function as a argument of another function setTimeout(function(){

console.log(‘it gets execute after 1 second’)

},1000);

Output:

Practical 5(f)

Code:

/* if you want anonymous function get create and execute immediately then do in this way */

(function(){

console.log(‘this is invoking function immediately after its creation’);

})();

Output:

Practical 5(g)

Code:

//scope of variable in function var firstname=‘manoj’; function myname(){

var firstname=‘rohit’; console.log(firstname);

}

myname(); console.log(firstname);

Output:

Practical 6: File Handling in Node js

File system in Node.js is used to read and write file by using the built-in fs module. It is also used to read or write files from console as well as to create new file in specific location and perform read and write operations on it.

Practical 6(a)

    1) File handling with read operations

Step 1-

Create myfile.txt and type following lines

This is the file that node js readstream will read the contents

thank you for this!!!!!!!!!!!!!!!!!!!!!!!!111

step 2 –

create file readstream.js and type following code

var fs = require (‘fs’);

var data=‘‘;

var readerStream =fs.createReadStream(‘myfile.txt’);

//encoding with utf8

readerStream.setEncoding(‘utf8’);

readerStream.on(“data”,function(chunk){

data+=chunk;

})

readerStream.on(“end”,function(){

console.log(data);

});

Step 3

Output

Practical 6(b) write file

    1) Create file output.txt (without contents)

    2) Create file writestream.js and write following code

Writestream.js

var fs= require(‘fs’);

var data=(“this is my data and this will help you to understand the stream concept in node js”);

var writerStream= fs.createWriteStream(‘output.txt’);

writerStream.write(data,‘utf8’);

writerStream.end();

writerStream.on(‘finish’, function(){

});

    3) Open output.txt

    4) Done

Practical 6(c) utf8

    1) Create demo.docs with following code

hello everyone

this file we will use for readwrite utf8 stream in node js

    2) Create readwriteutf8.js

var fs = require(‘fs’);

var readerStream = fs.createReadStream(‘demo.docs’);//create redable stream

var writerStream = fs.createWriteStream(‘myoutput.docs’);

readerStream.pipe(writerStream);

    3) Open myoutput.docs

Practical 7: HTTP Server in Node js

Node js has a built-in module called HTTP, which allows node js to transfer data over the Hyper Text Transfer Protocol. Using this module one can create REST API with Node js. It is basically used to communicate with client as well as the user.

Practical 7(a)

Code:

const http=require(‘http’);//including http module http.createServer((req,res) =>{

res.write(“Hello everyone”); res.end();

}).listen(5000);

console.log(‘Server is running properly on port 5000’);

Output:

Practical 7(b)

Code:

const http=require(‘http’);

const server=http.createServer(function(req,res){if(req.url==‘/’) {

res.writeHead(200,{‘Content-Type’: ‘text/html’}); res.write(‘<html><body><h1>This is home page.</h1></body></html>’); res.end();

}else if (req.url==“/contact”){res.writeHead(200,{‘Content-Type’: ‘text/html’});

res.write(‘<html><body><p>This is contact page</p></body></html>’); res.end();

}else if (req.url==“/admin”){res.writeHead(200,{‘Content-Type’: ‘text/html’});

res.write(‘<html><body><p>This is admin page</p></body></html>’); res.end();

} else {

res.end(‘Invalid request’);

}

});

server.listen(5000);

console.log(‘server running on port 5000’);

Output:

Practical 7(c)

Code:

var http=require(‘http’); var fs=require(‘fs’);

fs.readFile(‘./index.html’, function(err, html){if(err)

{

throw err;

}

http.createServer(function(request,response){response.writeHead(200)

response.writeHead(200,{‘content-type’: ‘text/html’}); response.write(html);

response.end();

}).listen(5000);

console.log(‘Server is running properly’);

});

Output:

Practical 7(d)

Code:

const express=require(‘express’); const app=express();

app.get(‘/’, (req,res)=> {

res.send(‘<h1><b><u>Good morning all</u></b></h1>’); res.send(req.header(‘Content-Type’))

})

app.listen(3000);

console.log(“Here we are running server with express”);

Output

Practical 8: Stream in Node js

A stream is a way of data-handling that helps us to obtain a sequential output by reading or writing the input (files, network communications, and any kind of end-to-end information exchange).

That is, they let you read data from a source or write it to a destination or perform any other specific task in an uninterrupted and constant manner.

The stream is not a unique concept to Node.js and it is a part of Unix for quite a long time.

A pipe operator is used to make the programs react with each other by passing streams. Hence, the Node.js stream is used as a basis for all streaming APIs.

Example: When you are streaming YouTube, Netflix, Spotify then, instead of the whole content downloading all at once, it downloads in small chunks while you keep browsing.

Another example can be chatting on Facebook or WhatsApp where the data is continuously flowing between two people.

This is because instead of reading all the data at once in the memory the stream processes it into smaller pieces to make large files easily readable. It is useful because some files are larger than the available free space that you have on your device. Hence, the stream makes such files readable.

Advantages of Stream:

    1. Memory efficiency: Stream is memory (spatial) efficient because they enable you to download files in smaller chunks instead of a whole in the memory before you can process it thus, saving space.

    2. Time efficiency: Stream is time-efficient because you start processing the data in smaller chunks so the procedure starts earlier compared to the general way, where you have to download the whole data to be able to process it. Hence, this early processing saves a lot of time.

    3. Composable data: Data is composed because of the piping ability of the streams which lets them connect together in spite of however heavy the codes. It means that the process of one input getting piped to output keeps on happening.

Types of Stream:

    1. Readable stream: It is the stream from where you can receive and read the data in an ordered fashion. However, you are not allowed to send anything. For example fs.createReadStream() lets us read the contents of a file.

    2. Writable stream: It is the stream where you can send data in an ordered fashion but you are not allowed to receive it back. For example fs.createWriteStream() lets us write data to a file.

    3. Duplex stream: It is the stream that is both readable and writable. Thus you can send in and receive data together. For example net.Socket is a TCP socket.

    4. Transform stream: It is the stream that is used to modify the data or transform it as it is read. The transform stream is basically duplex in nature. For example, zlib.createGzip stream is used to compress the data using gzip.

Different operations in a stream are:

    1. Reading from a stream: Create a file named input.txt with the following text: This is a code to learn about the reading from a stream.

Filename: main.js

edit close

play_arrow

link

var fs = require(“fs”);

var data = ‘‘;

// Create a readable stream

var readerStream = fs.createReadStream(“input.txt”);

// Set the encoding to be utf8.

readerStream.setEncoding(“UTF8”);

// Handling data stream event

readerStream.on(“data”, function(chunk) {

data += chunk;

});

// Handling end stream event

readerStream.on(“end”,function() {

console.log(data);

});

// Handling error stream event

readerStream.on(“error”, function(err) {

console.log(err.stack);

});

chevron_right

filter_none

Run main.js file with the following command:

$ node main.js

The output of the above command is shown below:

This is a code to learn about the reading from a stream.

    2. Writing to a stream

Filename: main.js

var fs = require(‘fs’);

var data = ‘This is a code to learn“

+ “ about writing in a stream.‘;

// Create a writable stream

var writerStream =

fs.createWriteStream(‘output.txt’);

// Write the data to stream with

// encoding to be utf8

writerStream.write(data, ‘UTF8’);

// Mark the end of file

writerStream.end();

// Handling finish stream event

writerStream.on(‘finish’, function () {

});

// Handling error stream event

writerStream.on(‘error’, function (err) {

console.log(err.stack);

});

chevron_right

filter_none

Run main.js file with the following command:

$ node main.js

After executing above command, a file named output.txt will be created in the current directory with the following text:

This is a code to learn about writing in a stream.

    3. Piping the stream: Piping is an operation or a mechanism where we provide the output of one stream (readable, i.e., the source file) of data as the input to another stream (write-able, i.e. the destination file). It is normally used to get data from one stream (i.e. read from source) and pass the output of that stream to another stream (i.e. write to destination) without managing the flow yourself. It is the easiest way to consume streams. There is no limit on piping operations. It is used to process streamed data in multiple ways. For example, reading from one file and writing it to another.

Create a file named input.txt with the following text:

This is a code to learn about piping the stream.

Filename: main.js

var fs = require(‘fs’);

// Create a readable stream

var readerStream = fs.createReadStream(‘input.txt’);

// Create a writable stream

var writerStream = fs.createWriteStream(‘output.txt’);

// Pipe the read and write operations

// read input.txt and write data to output.txt

readerStream.pipe(writerStream);

chevron_right

filter_none

Run main.js file with the following command:

$ node main.js

After executing above command, a file named output.txt will be created in current directory with the following text:

This is a code to learn about piping the stream.

    4. Chaining the stream: Chaining of the stream is a mechanism of creating a chain of multiple stream operations by connecting the output of one stream with another stream. It is normally used with piping operations. For example, we will use piping and chaining to first compress a file and then decompress the same.

Filename: main.js

var fs = require(‘fs’);

var zlib = require(‘zlib’);

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

fs.createReadStream(‘input.txt’)

.pipe(zlib.createGzip())

.pipe(fs.createWriteStream(‘input.txt.gz’));

console.log(‘File Compressed.’);

chevron_right

filter_none

Run main.js file with the following command:

$ node main.js

Output of above command is shown below:

File Compressed.

You will find that input.txt has been compressed and it created a file input.txt.gz in the current directory.

Now code to decompress the above created file is shown below: Filename: main.js

var fs = require(‘fs’);

var zlib = require(‘zlib’);

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

fs.createReadStream(‘input.txt.gz’)

.pipe(zlib.createGunzip())

.pipe(fs.createWriteStream(‘input.txt’));

console.log(‘File Decompressed.’);

chevron_right

filter_none

Run main.js file with the following command:

$ node main.js

Output of above command is shown below:

File Decompressed.

You will find that input.txt.gz has been decompressed.