0% found this document useful (0 votes)
474 views18 pages

SYBBA (CA) Nodejs PDF

The document provides code examples for various Node.js concepts like creating packages, requiring modules, connecting to MySQL databases, and handling HTTP requests. It also includes questions and explanations from a practical Node.js exam on topics like using modules, performing CRUD operations in databases, and building basic web servers and APIs. The code samples cover fundamental Node.js skills like importing and using packages, reading and writing files, making HTTP requests, and interacting with databases.

Uploaded by

RÃHÜL MÃGÏ
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
474 views18 pages

SYBBA (CA) Nodejs PDF

The document provides code examples for various Node.js concepts like creating packages, requiring modules, connecting to MySQL databases, and handling HTTP requests. It also includes questions and explanations from a practical Node.js exam on topics like using modules, performing CRUD operations in databases, and building basic web servers and APIs. The code samples cover fundamental Node.js skills like importing and using packages, reading and writing files, making HTTP requests, and interacting with databases.

Uploaded by

RÃHÜL MÃGÏ
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

SYBBA(CA) Practical

Subject:Nodejs

Code for up.js

Step 1)create packeje.json file

Vby typing following command

Npm init –y

Step 2)install package uppercase by using following command

Npm I uppercase

const up = require('upper-case')
console.log(up.upperCase("Hello world"));

QB)

var mysql = require('mysql');

var con = mysql.createConnection({

host : 'localhost',
user : 'root',
password : '',
database:'awani2'
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "CREATE TABLE customers (rollno VARCHAR(255), name VARCHAR(5))";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
Prof.D.G.Dhumal
Anantrao Thopte college,Bhor
Question 2

Code for

/factorial Using User Module with user input

var factorial = require('./fact.js');

var rl = require('readline').createInterface({

input: process.stdin,

output: process.stdout

});

rl.question('Enter The Number : ', x => {

var ans=factorial(x);

console.log(`Your Answer Is : ${ans}`);

rl.close();

});

……………………………………………………………………………………………………………………………………………………

Code for fact.js

module.exports = function factorial(x)

if (x === 0)

return 1;

return x * factorial(x-1);

}
Prof.D.G.Dhumal
Anantrao Thopte college,Bhor
Circleexp.js

module.exports = function areacircum(r){


pi = 3.14;
return [pi*(r*r) , 2*pi*r];
};

Prof.D.G.Dhumal
Anantrao Thopte college,Bhor
Slip 5 A

Prof.D.G.Dhumal
Anantrao Thopte college,Bhor
Q5B

var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "root",
password: "",
database: "customer2"
});

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");

//data insert
var data1 = "INSERT INTO customer2 (name, address) VALUES ('Samarth Mali',
'Nandurbar')";
var data2 = "INSERT INTO customer2 (name, address) VALUES ('Pratik Swami',
'Pune')";
var data3 = "INSERT INTO customer2 (name, address) VALUES ('Bhushan Deshmukh',
'Akola')";
con.query(data1, function (err, result) {
if (err) throw err;
console.log( "no. 1 record inserted");
});
con.query(data2, function (err, result) {
if (err) throw err;
console.log( "no. 2 record inserted");
});
con.query(data3, function (err, result) {
if (err) throw err;
console.log( "no. 3 record inserted");
});

//delete data
var row = "DELETE FROM customer2 WHERE address = 'Pune'";
con.query(row, function (err, data) {
if (err) throw err;
console.log("Number of records deleted: " + data.affectedRows);

});
Prof.D.G.Dhumal
});
Anantrao Thopte college,Bhor
Slip 6 A

var http = require('http');


var url = require('url');
var fs = require('fs');

http.createServer(function (req, res) {


var q = url.parse(req.url, true);
var filename = "slipno6.txt" + q.pathname;
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
res.end("404 Error");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(8080);

Prof.D.G.Dhumal
Anantrao Thopte college,Bhor
Slip 7 _A

var fs = require('fs');
var rl = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});

fs.appendFile('1.txt', '2.txt',function(err){
if(err) throw err;
});

Slip7 _B

var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "root",
password: "",
database: "slipno6"
});

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");

con.query("SELECT * FROM slipno6", function (err, result, fields) {


if (err) throw err;
console.log(result);
});

});

Slip8_A

Code for app.js

var express = require("express");


Prof.D.G.Dhumal
Anantrao Thopte college,Bhor
var multer = require('multer');
var app = express();
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.originalname);
}
});
var upload = multer({ storage : storage}).single('myfile');

app.get('/',function(req,res){
res.sendFile(__dirname + "/index1.html");
});

app.post('/upload',function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded successfully!");
});
});

app.listen(2000,function(){
console.log("Server is running on port 2000");
});

Code for index.html

<html>
<head>
<title>File upload in Node.js </title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script
src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"><
/script>
<script>
$(document).ready(function() {
$('#uploadForm').submit(function() {
$("#status").empty().text("File is uploading...");

Prof.D.G.Dhumal
Anantrao Thopte college,Bhor
$(this).ajaxSubmit({

error: function(xhr) {
status('Error: ' + xhr.status);
},

success: function(response) {
console.log(response)
$("#status").empty().text(response);
}
});

return false;
});
});
</script>
</head>
<body>
<h1>Express.js File Upload</h1>
<form id="uploadForm" enctype="multipart/form-data" action="/upload"
method="post">
<input type="file" name="myfile" /><br/><br/>
<input type="submit" value="Upload Image" name="submit"><br/><br/>
<span id="status"></span>
</form>
</body>
</html>

Slip 10

var download = require('image-downloader')

var options = {
url: 'https://i.ytimg.com/vi/6QcuNl1yXrw/maxresdefault.jpg',
dest: 'download/' // will be saved to /path/to/dest/image.jpg
}

download.image(options)
.then(({ filename }) => {
console.log('Saved to', filename) // saved to /path/to/dest/image.jpg
Prof.D.G.Dhumal
Anantrao Thopte college,Bhor
})

Slip no 11

var http = require('http');


var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('slip11.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);

Code for slip11.html

<!DOCTYPE html>
<html>
<head>
<title>form</title>
<style>
h1{text-align:center;
font-size:70px;
color:red;
}
p{
color:blue;
text-align:center;
font-size:20px;
text-decoration:underline}
h2{
text-align:center;
}
</style>
<body bgcolor=pink>
<h1>Anantrao Thopte College</h1>
<center><img src=c.gif height=350 width=350></center>
<p>
Rajgad Dnyanpeeth's<h2>
ANANTRAO THOPTE COLLEGE<br>
Prof.D.G.Dhumal
Anantrao Thopte college,Bhor
BHOR, DIST-PUNE 412206.<br>
Affiliated to Savitribai Phule Pune University, Accredited by NAAC 'A' Grade</p>
</h2>
<a href=demospa.html>Click Here For Registration</a></h2></body></html>

Slip no 12_B

const mysql = require("mysql");


const express = require("express");
const bodyParser = require("body-parser");
const encoder = bodyParser.urlencoded();

const app = express();

const con = mysql.createConnection({


host: "localhost",
user: "root",
password: "",
database: "nodejs"
});
con.connect(function(error){
if (error) throw error
else console.log("connected")
});

app.get("/",function(req,res){
res.sendFile(__dirname + "/index.html");
})
app.post("/",encoder, function(req,res){
var username = req.body.username;
var password = req.body.password;
con.query("select * from loginuser where user_name = ? and user_pass =
?",[username,password],function(error,results,fields){
if (results.length > 0) {
res.redirect("/loggedine");
} else {
res.redirect("/");
}
res.end();
})
})
app.get("/loggedine",function(req,res){
res.sendFile(__dirname + "/loggedine.html")
})
Prof.D.G.Dhumal
Anantrao Thopte college,Bhor
app.listen(8080);

Slip 13_A.js

// slip no 13 Area of rectangle Using User module

var http = require('http');


var arearrect = require('./rect');

var rl = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});

rl.question('Enter The length : ', (l) => {


rl.question('Enter The breath : ', (b) => {

var result = arearrect(l, b);

console.log(`Area Of Rectangle is : ${result}`);


rl.close();

http.createServer(function (req, res) {


res.writeHead(200, { 'Content-Type': 'text/html' });
res.write("Area Of Rectangle is : " + result);
res.end();
}).listen(8080);
});

});

Rect.js

module.exports = function arearrect(l,b){

return l*b;
Prof.D.G.Dhumal
Anantrao Thopte college,Bhor
};

Slip13_B

var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "root",
password: "",
database: "student"
});

con.connect(function(err) {
if (err) throw err;
var sql = "UPDATE student SET Marks = 90 WHERE Roll__num = 1";
con.query(sql, function (err, result,display) {
if (err) throw err;
console.log(result.affectedRows + " record updated");
});

con.query("SELECT *, name FROM student", function (err, result, fields) {


if (err) throw err;
console.log(result);
});
});

Slip14A

const fs = require("fs");

let file = fs.readFileSync("sam.txt", "utf8");


let arr = file.split(/\r?\n/);
arr.forEach((line, idx)=> {
if(line.includes("Naruto")){
console.log((idx+1)+':'+ line);
}
});

Prof.D.G.Dhumal
Anantrao Thopte college,Bhor
Slip 15

const fs = require("fs");

let file = fs.readFileSync("sam.txt", "utf8");


let arr = file.split(/\r?\n/);
arr.forEach((line, idx)=> {
if(line.includes("Naruto")){
console.log((idx+1)+':'+ line);
}
});

Slp 16B

var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "root",
password: "",
database: "employee_data"
});

con.connect(function(err) {
if (err) throw err;
var sql = "UPDATE Employee SET Sal = 50000 WHERE Eno = 1";
con.query(sql, function (err, result,display) {
if (err) throw err;
console.log(result.affectedRows + " record updated");
});

con.query("SELECT * FROM employee", function (err, result, fields) {


if (err) throw err;
console.log(result);
});
});

Prof.D.G.Dhumal
Anantrao Thopte college,Bhor
Slip17 B

var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "root",
password: "",
database: "slipno17B"
});

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");

con.query("CREATE DATABASE IF NOT EXISTS slipno17B", function (err, result) {


if (err) throw err;
console.log("Database created");
});

var sql = "CREATE TABLE IF NOT EXISTS Employee (name VARCHAR(255), sal
INT(20))";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});

var sql = "INSERT INTO Employee (name, sal) VALUES ?";


var data = [
['ABC', '9400'],
['XYZ', '4500'],
['PQR', '2300']
];

con.query(sql, [data] ,function (err, result) {


if (err) throw err;
console.log("record inserted");
});

con.query("SELECT * FROM Employee ORDER BY sal ASC", function (err, result,


fields) {
if (err) throw err;
console.log(result);

Prof.D.G.Dhumal
Anantrao Thopte college,Bhor
});
});

Slip22

var fs = require('fs');
filePath = process.argv[2];
File_sam = fs.readFileSync('./sam.txt');
to_string = File_sam.toString();
lines = to_string.split("\n");
console.log('No of lines is : ' + lines.length);

slip28

var fs = require("fs");
var buf = new Buffer(1024);
console.log("Going to open an existing file");
fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("File opened successfully!");
console.log("Going to truncate the file after 10 bytes");
// Truncate the opened file.
fs.ftruncate(fd, 10, function(err){
if (err){
console.log(err);
}
console.log("File truncated successfully.");
console.log("Going to read the same file");
fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){if (err){
console.log(err);
}
// Print only read bytes to avoid junk.
if(bytes > 0){
console.log(buf.slice(0, bytes).toString());
}
// Close the opened file.
Prof.D.G.Dhumal
Anantrao Thopte college,Bhor
fs.close(fd, function(err){
if (err){
console.log(err);
}
console.log("File closed successfully.");
});
});
});
});

Slip 29

// slip no 13 Area of rectangle Using User module

var http = require('http');


var arearrect = require('./rect');

var rl = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});

rl.question('Enter The length : ', (l) => {


rl.question('Enter The breath : ', (b) => {

var result = arearrect(l, b);

console.log(`Area Of Rectangle is : ${result}`);


rl.close();

http.createServer(function (req, res) {


res.writeHead(200, { 'Content-Type': 'text/html' });
res.write("Area Of Rectangle is : " + result);
res.end();
}).listen(3000);
});

});

Prof.D.G.Dhumal
Anantrao Thopte college,Bhor
Prof.D.G.Dhumal
Anantrao Thopte college,Bhor

You might also like