#37 Node Pract
#37 Node Pract
Practical 1
Steps to download node.js
Step 1) Download Node.js Installer for Windows Go to the
site https://nodejs.org/en/download/ and download the necessary binary files.
Step 2) Run the installation Double click on the downloaded .msi file to start the installation.
Click the Run button on the first screen to begin the installation.
Step 3) Continue with the installation steps In the next screen, click the “Next” button to
continue with the Node.js download and installation
FYMCA DIV-A 37
Step 4) Accept the terms and conditions In the next screen, Accept the license agreement and
click on the Next button
Step 5) Set up the path In the next screen, choose the location where Node.js needs to be
installed and then click on the Next button.
Step 6) Select the default components to be installed Accept the default components and
click on the Next button.
FYMCA DIV-A 37
Step 7) Start the installation In the next screen, click the Node.js install button to start
installing on Windows
Step 8) Complete the installation Click the Finish button to complete the installation.
Complete the installation Click the Finish button to complete the installation.
FYMCA DIV-A 37
Practical 2
Steps to download visual studio
Step 1: Visit the official website of the Visual Studio Code using any web browser like
Google Chrome, Microsoft Edge, etc. and Press the “Download for Windows” button
Step 2:When the download finishes, then the Visual Studio Code icon appears in the
downloads folder. Click on the installer icon to start the installation process of the Visual
Studio Code. After the Installer opens, it will ask you for accepting the terms and conditions
of the Visual Studio Code. Click on and then click the button.
FYMCA DIV-A 37
Step 3: 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 4: Then it will ask for beginning the installing setup. Click on the Install button.
After clicking on Install, it will take about 1 minute to install the Visual Studio Code on
your device.
Step 5: 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.
FYMCA DIV-A 37
Practical 3
Demonstrate the basic arithmetic operations in Node.js
function sum(a, b) {
return a + b;
}
function sub(a, b) {
return a - b;
}
function mul(a, b) {
return a * b;
}
function div(a, b) {
return a / b;
}
console.log("Addition: ", sum(5, 5));
console.log("Subtraction: ", sub(3, 2));
console.log("Multiplication", mul(4, 8));
console.log("Division: ", div(6, 2));
Output:
FYMCA DIV-A 37
Practical 4
To determine whether a given number is even or odd in
Node.js
function displayresult(a) {
console.log(a);
}
function check(num) {
let sum = num;
if (num % 2 == 0) {
console.log("Number is Even")
} else {
console.log("Number is odd")
}
}
check(18, displayresult)
Output:
FYMCA DIV-A 37
Practical 5
To print all prime numbers up to a given number in
Node.js
function isPrime(n)
{if(n==1||n==0) return false;
for(var i=2;i<n;i++){
if(n%i==0) return false;
} return true;
}
var num =30;
for(var i=1;i<=num;i++){
if(isPrime(i)){
console.log(i);
}
}
Output:
FYMCA DIV-A 37
Practical 6
Create an application in NodeJS to reverse the given number and display it
(Note: 5 digit number)
var number = 12345;
var reversedNumber = number.toString().split('').reverse().join('');
console.log('Reversed number is: ' + reversedNumber);
Output :
FYMCA DIV-A 37
Practical 7
Create an application in Node.js to display Armstrong
number 15
function isArmstrongNumber(num) {
let sum = 0;
const strNum = String(num);
const len = strNum.length;
function printFirstNArmstrongNumbers(n) {
let count = 0;
let num = 1;
printFirstNArmstrongNumbers(15);
Output:
FYMCA DIV-A 37
Practical 8
To generate the first 10 numbers in the Fibonacci sequence
in Node.js
var a=0;
var b=1;
var c;
console.log(a);
console.log(b);
for(i=0;i<8;i++)
{
c=a+b;
console.log(c);
a=b;
b=c;
}
Output:
FYMCA DIV-A 37
Practical 9
To demonstrate the use of setTimeout and arrow functions
in Node.js
}
setTimeout(message,5000);
setTimeout(()=> {
console.log("Calling from Arrow function");
},8000);
Output:
FYMCA DIV-A 37
Practical 10
function add(a,b){
return a+b;
}
exports.add=add;
Output:
FYMCA DIV-A 37
Practical 11
write an application to find area of circle, square,
rectangle using module in Node.js
function square(s){
return s*s;
}
function rectangle(l,b){
return l*b;
}
function circle(r){
return 3.14*r*r;
}
exports.square=square;
exports.rectangle=rectangle;
exports.circle=circle;
sRES=req.square(5);
rRes=req.rectangle(4,6);
cRes=req.circle(4);
console.log("square:",sRES);
console.log("rectangle:",rRes);
console.log("circle:",cRes);
Output:
FYMCA DIV-A 37
Practical 12
Write an application to demonstrate events module in
Node.js
//REGISTER
emitter.on('messageLogged',function (){
console.log('Listener called');
});
//Raise
emitter.emit('messageLogged')
Output:
FYMCA DIV-A 37
Practical 13
write an application to demonstrate function
(removeListner, listnerCount) in Node.js
eventEmitter.removeListener("write",listner1);
console.log("Listner1 is removed");
eventEmitter.emit("write");
console.log(eventEmitter.listenerCount("write"));
console.log("program Ended.....")
Output:
FYMCA DIV-A 37
Practical 14
create an application in node.js to Return Event Emitter
Output:
FYMCA DIV-A 37
Practical 15
create an application in node.js to create Extend Event
Emitter in Node.js
var emitter=require('events').EventEmitter;
var util = require('util');
function LoopProcessor (num) {
var me = this;
setTimeout(function(){
for (var i=1;i<=num;i++){
me.emit ('BeforeProcess',i);
console.log('processing number: '+i);
me.emit ('After Process',i);
}
}, 2000)
return this;
}
util.inherits (LoopProcessor, emitter)
var lp = new LoopProcessor (3);
lp.on('BeforceProcess', function(data) {
console.log('About to start the process for' + data);
});
lp.on('AfterProcess', function(data) {
console.log('completed processing '+ data);
});
Output:
FYMCA DIV-A 37
Practical 16
Write an event emitter code to design an event called as
“calculate Salary” which is used to calculate the salary of
an employee by passing some arguments like Basic Salary,
HRA (20% of Basic), DA(100% of Basic), TA, and
deductions like Income Tax (30% of Basic) and
Professional Tax of 200.
const EventEmitter = require('events');
// Example usage:
salaryCalculator.calculateSalary(50000, 8000); // Basic Salary is 50000 and TA is
8000
Output
FYMCA DIV-A 37
Practical 17
create an application in node.js to display message after 5
second &10 second
Output:
FYMCA DIV-A 37
Practical 18
create an application in node.js to demonstrate set interval
function
setInterval(
() => console.log('Hello After 4 Second'),4000
);
Output:
FYMCA DIV-A 37
Practical 19
create an application in node.js to display factorial of a
number
function factorial(n){
let i=n;
let res=1;
while(i>+1){
res = res*i;
i--
}
return res;
}
const num = 6;
const result = factorial(num);
console.log(result);
Output:
FYMCA DIV-A 37
Practical 20
Write as application to create http Server and Display
message in Node.js
var http = require('http');
var server = http.createServer(function(req,res){
res.write("Hello Mr.Raj");
res.end();
});
server.listen(5000);
console.log('Node.js web server at port 5000 is
running.. http://localhost:5000/')
Output:
FYMCA DIV-A 37
Practical 21
Write a Node.js code to display Employee Job Registration
Form saved in an HTML file in response to the client’s
access request to the server.
const http = require('http');
const fs = require('fs');
Output :
FYMCA DIV-A 37
Practical 22
Write as application to create Home page, Admin page
and Student page using http server in Node.js.
else if(req.url=='/home')
{
res.writeHead(200,{'content-type':'text/html'});
res.write('<html><head><style>body{padding-left: 43px; padding-
right:43px; background-color:lightyellow;} </style></head><body><p><h1>This is
home page</h1></p><h1>Raj Pawar</h1><h3>This page is a brief insight to who I
am.</h3>');
res.write('<nav style="background-color:white; text-
align:center;"><ul><li><a href="/">Start Page</a></li><li><a
href="/student">Student</a></li><li><a
href="/admin">Admin</a></li></ul></nav></body></html>');
res.end();
}
else if (req.url=='/student')
{
res.writeHead(200,{'content-type':'text/html'});
res.write('<div style="display: inline-block; float: right; height:
40px; padding: 20px;"><ul><li><a href="/home">Home</a></li><li><a
href="/">Start Page</a></li> <li><a href="/admin">Contact
Admin</a></li></ul></div>');
res.write('<html><head><style>body{background-
color:pink;}</style><title>Form</title></head><body bgcolor="White" ><h1
align="center">Student Page Form</h1>');
FYMCA DIV-A 37
res.write('<div class="input_field"><h3>Password</h3></div><div
class="input_field"><input type="Password"');
res.write('name="pword" placeholder="Password" required/></div><p>');
res.write('<style>button{border:none; border-radius:5px; text-
align:center; padding:15px 15px; background-
color:lavender;<div></div></style>');
res.write('<button onclick=alert("SUCESS")>LOGIN
NOW</button></form>');
res.end();
}
else{
res.end('Invalid request');
}
});
server.listen(9000);
console.log('Node.js web server at port 9000 is running');
Output:
FYMCA DIV-A 37
Practical 23
Write in application to display details of the current file
path in Node.js.
Output:
FYMCA DIV-A 37
Practical 24
Write an application to read file in Node.js.
const fs = require('fs');
fs.readFile("_txt.txt",'utf8',function(err,data)
{
console.log("Reading File");
console.log(data);
});
Output:
FYMCA DIV-A 37
Practical 25
Write an application to write in file in Node.js.
const fs = require("fs");
Output:
FYMCA DIV-A 37
Practical 26
Write an application to add data in file in Node.js.
const fs = require("fs");
fs.appendFile("_txt.txt","\nHello Everyone \nLet's play agian",
function (err,data){
console.log("append file");
});
Output:
FYMCA DIV-A 37
Practical 27
Write an application to delete a file in Node.js.
const fs = require("fs");
fs.unlink("txt2.txt",function(err,data)
{
console.log("Deleting File");
console.log("File Deleted Succesfully");
});
Output:
FYMCA DIV-A 37
Practical 28
Combine Read, Write, Append, Delete file in one program
in Node.js
const fs = require("fs");
fs.readFile("_com.txt",'utf8',function(err,data)
{
console.log("Reading File");
console.log(data);
});
fs.unlink("_com.txt",function(err,data)
{
console.log("Deleting File");
console.log("File Deleted Succesfully");
});
Output:
FYMCA DIV-A 37
Practical 29
Write and application to rename a file in Node.js
var fs = require('fs')
fs.rename('_txt.txt','Mr_raj.txt',function(err){
if(err) throw err;
console.log('Filed Rename')
});
Output:
FYMCA DIV-A 37
Practical 30
Create an Application to create Database in Node.js
var mysql = require('mysql')
var con = mysql.createConnection({
host:'localhost',
user:'root',
password:'root'
});
con.connect(function(err){
if(err){ throw err;}
else{
console.log("connected");}
con.query("CREATE DATABASE STUDENTS4", function(err,result){
if(err) throw err;
console.log("Database Created");
});
});
Output:
FYMCA DIV-A 37
Practical 31
Create an Application to create Student table with
columns as id, name, address, course, contact in Node.js
var mysql=require('mysql');
var con=mysql.createConnection
(
{
host:'localhost',
user:'root',
password:'root',
database:'students4'
}
);
con.connect(function(err)
{
if(err) throw err;
console.log("connected...");
var sql = "CREATE TABLE student1(id INT(10) PRIMARY KEY
AUTO_INCREMENT,name VARCHAR(255), address VARCHAR(255),course VARCHAR(20),
contact INT(15))";
con.query(sql,function(err,result)
{
if(err) throw err;
console.log("table created...");
});
});
Output:
FYMCA DIV-A 37
Practical 32
Create an Application to insert rows into Student table in
Node.js
var mysql=require('mysql');
var con=mysql.createConnection
(
{
host:'localhost',
user:'root',
password:'root',
database:'students4'
}
);
con.connect(function(err)
{
if(err) throw err;
console.log("connected...");
var sql2 = "INSERT INTO student1(id ,name , address,course , contact)
VALUES('1','raj','thane','MCA','1234567890')";
con.query(sql2,function(err,result)
{
if(err) throw err;
console.log()
console.log("row inserted successfuly...");
});
});
Output:
FYMCA DIV-A 37
Practical 33
Create an Application to display rows into Student table in
Node.js
var mysql=require('mysql');
var con=mysql.createConnection
(
{
host:'localhost',
user:'root',
password:'root',
database:'students4'
}
);
con.connect(function(err)
{
if(err) throw err;
console.log("connected...");
var sql2="select * from student1";
con.query(sql2,function(err,result)
{
if(err) throw err;
console.log(result);
});
});
Output:
FYMCA DIV-A 37
Practical 34
Create an Application to Update rows in Student table in
Node.js
var mysql=require('mysql');
var con=mysql.createConnection
(
{
host:'localhost',
user:'root',
password:'root',
database:'students4'
}
);
con.connect(function(err)
{
if(err) throw err;
console.log("connected...");
var sql2= "UPDATE student1 SET course ='MMS' WHERE ID='1'";
con.query(sql2,function(err,result)
{
if(err) throw err;
console.log(result);
});
});
Output:
FYMCA DIV-A 37
Practical 35
Write a Node.js application to retrieve and update the
record related to the entries received for the conference
participation. Update the mobile number of participant
whose name is “Sharma
Practical 36
Create an Application to add column to Student table in
Node.js
var mysql=require('mysql');
var con=mysql.createConnection
(
{
host:'localhost',
user:'root',
password:'root',
database:'students4'
}
);
con.connect(function(err)
{
if(err) throw err;
console.log("connected...");
var sql = "ALTER TABLE student1 ADD age INT(5)";
con.query(sql,function(err,result)
{
if(err) throw err;
console.log("column inserted successfuly...");
});
});
Output:
FYMCA DIV-A 37
Practical 37
Create an Application to delete records in Student table in
Node.js
var mysql=require('mysql');
var con=mysql.createConnection
(
{
host:'localhost',
user:'root',
password:'root',
database:'students4'
}
);
con.connect(function(err)
{
if(err) throw err;
console.log("connected...");
var sql= "DELETE FROM student1 WHERE ID='1'";
con.query(sql,function(err,result)
{
if(err) throw err;
console.log("row deleted successfuly...");
});
});
Output: