SYBBA(CA) Sem IV Node Js slips solutions
Slip No 1
Q1.a Create a
Node.js file that will convert the output "Hello World!" into
upper-case letters.
var http =
require('http');
var uc =
require('upper-case');
http.createServer(function
(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(uc.upperCase("Hello World!"));
res.end();
}).listen(8080);
Save the code above in a file called "d_uppercase.js", and
initiate the file:
First install upper-case module
C:\Users\Your Name>npm upper-case
Initiate d_uppercase:
C:\Users\Your Name>node d_uppercase.js
If you have followed the same steps on your computer, you will see the the same result as the example:
b) Create a Node.js
file that demonstrate create database student DB and student table (Rno,
Sname,Percentage ) in MySQL.
create_db.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("CREATE DATABASE studentdb", function (err,
result) {
if (err) throw err;
console.log("Database created");
});
});
create_table.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "studentdb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "CREATE TABLE student(rollno int,name
VARCHAR(255), percentage double)";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
Initiate :
C:\Users\Your Name>node create_db.js
C:\Users\Your Name>node create_table.js
Slip No.2A.Create a Node.js Application
that uses user defined module to return the factorial of given number.
fact.js
var fact={
factorial: function(n)
{
var f=1,i;
for(i=1;i<=n;i++)
{
f=f*i;
}
console.log('factorial of '+n+'
is:'+f);}};
module.exports=fact
app.js
var
mymod=require('C:/Users/Public/node_prog/fact.js');
mymod.factorial(5);
Initiate app.js file :
C:\Users\Your Name>node app.js
b) Create NodeJS application
that contain the employee registration details and write a javascript to
validate DOB, Joining date and salary.
// employeeRegistration.js
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function registerEmployee() {
rl.question('Enter employee name: ', (name) => {
rl.question('Enter Date of Birth (YYYY-MM-DD): ',
(dob) => {
rl.question('Enter Joining Date (YYYY-MM-DD): ',
(joiningDate) => {
rl.question('Enter Salary: ', (salary) => {
if (!isValidDate(dob) || !isValidDate(joiningDate)
|| !isValidSalary(salary)) {
console.log('Invalid input. Please try again.');
rl.close();
return;
}
// Display employee details
console.log('\nEmployee Details:');
console.log('Name: ${name}`);
console.log('Date of Birth: ${dob}');
console.log('Joining Date: ${joiningDate}');
console.log('Salary: ${salary}');
rl.close();
});
});
});
});
}
function isValidDate(dateString) {
return /^\d{4}-\d{2}-\d{2}$/.test(dateString);
}
function isValidSalary(salary) {
return /^\d+$/.test(salary) &&
parseInt(salary) > 0;
}
// Start the employee registration process
registerEmployee();
Node JS
Slip No.3 and Slip no. 30 A.Create a
Node.js Application that uses user defined module circle.js which exports
functions area() and circumference() and display details on console.
circle.js
var circle={
area: function(r)
{
var
pi=3.14,a;
a=pi*r*r;
console.log('area of circle
is:'+a);
},
circumference: function(r)
{
var pi=3.14,c;
c=2*pi*r;
console.log('circumference of
circle is:'+c);
}
};
module.exports=circle
mycircle.js
var
mymod=require('C:/Users/Public/node_prog/circle.js');
mymod.area(5);
mymod.circumference(5);
Initiate mycircle.js file :
C:\Users\Your Name>node mycircle.js
b) Create NodeJS application
for validating student registration form.
// studentRegistration.js
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Function to validate student registration form
function validateStudentForm() {
rl.question('Enter student name: ', (name) => {
rl.question('Enter age: ', (age) => {
rl.question('Enter email: ', (email) => {
if (isValidAge(age) && isValidEmail(email))
{
// Display success message
console.log('\nStudent Registration Successful!');
console.log(`Name: ${name}`);
console.log(`Age: ${age}`);
console.log(`Email: ${email}`);
rl.close();
}
else {
console.log('Invalid input. Please check your age
and email format.');
rl.close();
}
});
});
});
}
// Function to validate age (must be a positive
integer)
function isValidAge(age) {
return /^\d+$/.test(age) && parseInt(age)
> 0;
}
// Function to validate email format
function isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
// Start the student registration form validation
process
validateStudentForm();
Slip 4
Create nodeJS application that accepts first name,last name and DOB of a person & define a module that concatnate first name and last name and also calculate the age of the person.
Create a file named studentRegistration.js:
// studentRegistration.js
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Function to validate student registration form
function validateStudentForm() {
rl.question('Enter student name: ', (name) => {
rl.question('Enter age: ', (age) => {
rl.question('Enter email: ', (email) => {
if (isValidAge(age) && isValidEmail(email)) {
// Display success message
console.log('\nStudent Registration Successful!');
console.log(`Name: ${name}`);
console.log(`Age: ${age}`);
console.log(`Email: ${email}`);
rl.close();
}
else {
console.log('Invalid input. Please check your age and email format.');
rl.close();
}
});
});
});
}
// Function to validate age (must be a positive integer)
function isValidAge(age) {
return /^\d+$/.test(age) && parseInt(age) > 0;
}
// Function to validate email format
function isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
// Start the student registration form validation process
validateStudentForm();
b) Create teacher profile system.
Create a file named teacherProfileSystem.js:
// teacherProfileSystem.js
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Function to create and display a teacher profile
function createTeacherProfile() {
rl.question('Enter teacher name: ', (name) => {
rl.question('Enter subject: ', (subject) => {
rl.question('Enter years of experience: ', (experience) => {
// Display teacher profile
console.log('\nTeacher Profile:');
console.log('Name: ${name}');
console.log('Subject: ${subject}');
console.log('Experience: ${experience} years');
rl.close();
});
});
});
}
// Start the teacher profile creation process
createTeacherProfile();
Slip No.5. a . Create a Node.js
Application that performs following operations on buffer data
a. concat b.compare
c. copy
buffer_op.js
var buffer1 = new
Buffer('TutorialsPoint ');
var buffer2 = new Buffer('Simply Easy
Learning');
var buffer3 =
Buffer.concat([buffer1,buffer2]);
console.log("buffer3 content:
" + buffer3.toString());
var result = buffer1.compare(buffer2);
if(result < 0) {
console.log(buffer1
+" comes before " + buffer2);
} else if(result === 0) {
console.log(buffer1
+" is same as " + buffer2);
} else {
console.log(buffer1
+" comes after " + buffer2);
}
buffer1.copy(buffer2);
console.log("buffer2 content:
" + buffer2.toString());
Initiate buffer_op.js file :
C:\Users\Your Name>node buffer_op.js
b) Create a Node.js file that Insert Multiple Records in
"student" table, and display the result object on console.
insert_record.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "studentdb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO student (rollno,name, percentage)
VALUES ?";
var values = [
[1,'abc', 77.6],
[2,'def', 89.6],
[3,'ghi', 91.6]
];
con.query(sql, [values], function (err, result)
{
if (err) throw err;
console.log("Number of records inserted: " +
result.affectedRows);
});
con.query("SELECT * FROM student", function (err, result,
fields) {
if (err) throw err;
console.log(result);
});
});
Initiate :
C:\Users\Your Name>node
insert_record.js
Slip No.6. a.Create a Node.js
Application that opens the requested file and returns the content to the client
if anything goes wrong throw 404 error.
demo_server.js
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 = "." +
q.pathname;
fs.readFile(filename,
function(err, data) {
if (err) {
res.writeHead(404,
{'Content-Type': 'text/html'});
return
res.end("404 Not Found");
}
res.writeHead(200,
{'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
Initiate demo_server.js file :
C:\Users\Your Name>node
demo_server.js
b) Create a Node js
file that Select all records from the "customers" table, and display
the result object on console.
all_cust.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err,
result, fields) {
if (err) throw err;
console.log(result);
});
});
Initiate :
C:\Users\Your Name>node all_cust.js
Slip 7
Create nodejs to read two file names from user and append contents of first file into second file .
const readline = require('readline');
const fs = require('fs/promises');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
async function appendFiles() {
try {
const file1 = await askQuestion('Enter the name of the first file: ');
const file2 = await askQuestion('Enter the name of the second file: ');
const contentToAppend = await fs.readFile(file1, 'utf-8');
await fs.appendFile(file2, contentToAppend);
console.log('Files appended successfully!');
rl.close();
} catch (error) {
console.error('Error:', error.message);
rl.close();
}
}
function askQuestion(question) {
return new Promise(resolve => {
rl.question(question, resolve);
});
}
appendFiles();
b) Create a Node js file that Select all records from the "customers" table, and display the result object on console.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
Slip 8 A using node.js create a ebpage to read 2 file names from user and combine third file with all the content into uppercase.
const fs = require('fs');
const readline = require('readline');
// Create a readline interface to read user input
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
// Prompt the user for file names
rl.question('Enter the first file name: ', (file1) => {
rl.question('Enter the second file name: ', (file2) => {
// Read the contents of the first file
fs.readFile(file1, 'utf-8', (err1, data1) => {
if (err1) {
console.error(`Error reading ${file1}: ${err1.message}`);
rl.close();
return;
}
// Read the contents of the second file
fs.readFile(file2, 'utf-8', (err2, data2) => {
if (err2) {
console.error(`Error reading ${file2}: ${err2.message}`);
rl.close();
return;
}
// Combine the contents and convert to uppercase
const combinedContent = `${data1}${data2}`.toUpperCase();
// Write the combined content to a third file
const outputFile = 'combined_output.txt';
fs.writeFile(outputFile, combinedContent, (err3) => {
if (err3) {
console.error(`Error writing to ${outputFile}: ${err3.message}`);
} else {
console.log(`Combined content written to ${outputFile}.`);
}
rl.close();
});
});
});
});
});
B create node.js application that contain student registration details & validate student firstname & lastname should not contains any special symbols/digits & age should be between 6 to 25
Install Dependencies: First, create a new Node.js project (if you haven’t already) and install the necessary dependencies:
npm init -y
npm install express express-validator
Create an HTML Form: Create an HTML form that collects student details. We’ll validate the first name, last name, and age.
HTML
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Registration</title>
</head>
<body>
<h2>STUDENT REGISTRATION FORM</h2>
<form action="/register" method="post">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName" required pattern="[A-Za-z]+">
<br>
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" name="lastName" required pattern="[A-Za-z]+">
<br>
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="6" max="25" required>
<br>
<input type="submit" value="Register">
</form>
</body>
</html>
AI-generated code. Review and use carefully. More info on FAQ.
Create Express Routes: Set up your Express server and handle the form submission. Validate the input using Express Validator middleware.
JavaScript
// server.js
const express = require('express');
const { body, validationResult } = require('express-validator');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.post('/register', [
body('firstName').isAlpha().withMessage('First name should contain only alphabets'),
body('lastName').isAlpha().withMessage('Last name should contain only alphabets'),
body('age').isInt({ min: 6, max: 25 }).withMessage('Age must be between 6 and 25'),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Save student details to database or perform other actions
res.send('Registration successful!');
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
AI-generated code. Review and use carefully. More info on FAQ.
Run Your Application: Start your Node.js server:
node server.js
Visit http://localhost:3000
Slip No.9. A.Create a Node.js file
that writes HTML form with an upload field.
upload.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload"
method="post" enctype="multipart/form-data">');
res.write('<input type="file"
name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}).listen(8080);
Initiate upload.js file :
C:\Users\Your Name>node upload.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
app.use(bodyParser.json());
const recipes = [
{
name: "Pasta Carbonara",
ingredients: ["Spaghetti", "Eggs", "Bacon", "Parmesan cheese", "Black pepper"],
instructions: "Cook the spaghetti. Meanwhile, fry the bacon. Mix eggs, cheese, and pepper. Combine all ingredients and serve."
},
{
name: "Chicken Stir-Fry",
ingredients: ["Chicken breast", "Broccoli", "Bell peppers", "Soy sauce", "Garlic", "Ginger"],
instructions: "Slice chicken and stir-fry until cooked. Add vegetables, soy sauce, garlic, and ginger. Cook until vegetables are tender."
},
// Add more recipes as needed
];
// Get all recipes
app.get('/recipes', (req, res) => {
res.json(recipes);
});
// Add a new recipe
app.post('/recipes', (req, res) => {
const newRecipe = req.body;
recipes.push(newRecipe);
res.json({ message: 'Recipe added successfully', recipe: newRecipe });
});
// Search for a specific recipe
app.get('/recipes/:name', (req, res) => {
const recipeName = req.params.name.toLowerCase();
const recipe = recipes.find(r => r.name.toLowerCase() === recipeName);
if (recipe) {
res.json(recipe);
} else {
res.status(404).json({ error: 'Recipe not found' });
}
});
app.listen(port, () => {
console.log('Server is running at http://localhost:${port}');
});
Slip No.10. A.Create a Node.js
application to download jpg image from server.
download_jpg.js
var fs = require('fs'),
request = require('request');
var download = function(uri, filename, callback){
request.head(uri, function(err, res, body){
console.log('content-type:',
res.headers['content-type']);
console.log('content-length:',
res.headers['content-length']);
request(uri).pipe(fs.createWriteStream(filename)).on('close',
callback);
});
};
download('https://www.google.com/images/srpr/logo3w.png', 'google.png',
function(){
console.log('done');
});
Install request module
First install request module
C:\Users\Your Name>npm request
Then initiate
C:\Users\Your Name>node download_jpg.js
Create simple web server using nodejs that shows the college information
const express = require('express');
const app = express();
const port = 3000;
// College information
const collegeInfo = {
name: 'PCCCS',
location: 'CHINCHWAD',
founded: 2000,
departments: ['Computer Science', 'BBA', 'COMMERCE'],
};
// Serve college information
app.get('/college', (req, res) => {
res.json(collegeInfo);
});
app.listen(port, () => {
console.log('Server is running at http://localhost:${port}');
});
b) using nodejs create computer science department portal.
const express = require('express');
const app = express();
const port = 3000;
// Sample data for courses and faculty
const courses = [
{ id: 1, name: 'Introduction to Programming', credits: 3 },
{ id: 2, name: 'Data Structures', credits: 4 },
{ id: 3, name: 'Database Management', credits: 3 },
];
const faculty = [
{ id: 101, name: 'Mrs. Swapnal Nagwade ', specialization: 'Algorithms' },
{ id: 102, name: 'Mrs. Hemalata Chavan', specialization: 'Database Systems' },
];
// Serve the home page
app.get('/', (req, res) => {
res.send('Welcome to the Computer Science Department Portal');
});
// Serve a list of courses
app.get('/courses', (req, res) => {
res.json(courses);
});
// Serve a list of faculty members
app.get('/faculty', (req, res) => {
res.json(faculty);
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
A create node.js application to bind two listners to single event.
B Using node.js create user login system
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");
})
app.listen(8080);
index.html
<html>
<body>
<form action="/" method="POST">
<input type="text" name="username" class="input-field" placeholder="username"/>
<input type="password" name="password" class="input-field" placeholder="password
<button type="submit" value="login">login
</form>
</body>
</html>
loggedine.html
<html>
<body>
<h1>welcome successfully login</h1>
</form>
</body>
</html>
Slip No.13 and Slipn no.29. A Create
a Node.js application that uses user defined module to find area of rectangle
and display details on console.
rect.js
var rect={
area: function(l,b)
{
var a;
a=l*b;
console.log('area of
rectangle is:'+a);
}
};
module.exports=rect
myrect.js
var
mymod=require('C:/Users/Public/node_prog/rect.js');
mymod.area(5,4);
Initiate myrect.js file :
C:\Users\Your
Name>node myrect.js
b) create nodejs application that pdate marks of given student rno in student table and display the result.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
app.use(bodyParser.json());
let students = [
{ rno: 1, name: 'John Doe', marks: 85 },
{ rno: 2, name: 'Jane Doe', marks: 92 },
];
app.get('/', (req, res) => {
res.send('Welcome to the Student Information System');
});
app.get('/students', (req, res) => {
res.json(students);
});
app.put('/students/:rno', (req, res) => {
const { rno } = req.params;
const { marks } = req.body;
const student = students.find(s => s.rno == rno);
if (student) {
student.marks = marks;
res.json({ message: 'Marks updated successfully', updatedStudent: student });
} else {
res.status(404).json({ error: 'Student not found' });
}
});
app.listen(port, () => {
console.log('Server is running at http://localhost:${port}');
});
Slip No.14. A Create a Node.js
application to search particular word in fille and display result on console.
search_word.js
var fs=require('fs');
fs.readFile('C:/Users/Public/node_prog/searchf.txt', function (err,
data) {
if (err) throw err;
if(data.includes('dfgdf')){
console.log(data.toString())
}
else
{
console.log('word not found');
}
});
Initiate search_word.js:
C:\Users\Your
Name>node search_word.js
Using NodejS create an Electricity bill system.
You might have files for handling input (app.js), calculating bills (billCalculator.js), and possibly for storing and retrieving data.
//app.js
const readline = require('readline');
const { calculateBill } = require('./billCalculator');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the number of units consumed: ', (units) => {
const billAmount = calculateBill(units);
console.log('Your electricity bill amount is: $${billAmount.toFixed(2)}');
rl.close();
});
//billCalculator.js
function calculateBill(units) {
let billAmount = 0;
if (units <= 100) {
billAmount = units * 1.50; // Replace 1.50 with your applicable rate
} else if (units <= 200) {
billAmount = 100 * 1.50 + (units - 100) * 2.00; // First 100 units at 1.50, remaining at 2.00
} else if (units <= 300) {
billAmount = 100 * 1.50 + 100 * 2.00 + (units - 200) * 2.50; // First 100 units at 1.50, next 100 at 2.00, remaining at 2.50
} else {
billAmount = 100 * 1.50 + 100 * 2.00 + 100 * 2.50 + (units - 300) * 3.00; // First 100 units at 1.50, next 100 at 2.00, next 100 at 2.50, remaining at 3.00
}
return billAmount;
}
module.exports = { calculateBill };
Slip 15 A create node.js application to count occurance of given word in a file & display count on console.
var fs=require("fs");
function countOcc(string,word){
return string.split(word).length-1;
}
var text=fs.readFileSync('programming.txt','utf8');
var count=countOcc(text,"is");
if(count==0){
console.log("not found");
}else{
console.log(count);
}
Slip 16 A event –driven application
B create node.js file that selects all records from table employee & update salary of given emp.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "empdb"
});
con.connect(function(err) {
if (err) throw err;
var sql = "update employee set sal=500000 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);
});
});
Slip 17 B using node.js display emp details order by salary in table.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("CREATE DATABASE empdb", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
var sql = "CREATE TABLE employee(name VARCHAR(255), salary int(20))";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
var sql = "INSERT INTO employee (name, salary) VALUES ?";
var values = [
['abc',7000],
['def', 9000],
['ghi', 1000]
];
con.query(sql, [values], function (err, result)
{
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
con.query("SELECT * FROM employee order by salary asc", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
Slip No.22. A Create a Node.js
application to count no of lines in a file in fille and display count on console
linecount.js
const readline = require('readline');
const fs = require('fs');
var file = 'C:/Users/Public/node_prog/searchf.txt';
var linesCount = 0;
var rl = readline.createInterface({
input: fs.createReadStream(file),
output: process.stdout,
terminal: false
});
rl.on('line', function (line) {
linesCount++; // on each linebreak, add +1 to
'linesCount'
});
rl.on('close', function () {
console.log(linesCount); // print the result
when the 'close' event is called
});
Install readline module
C:\Users\Your Name>npm readline
Then initiate
C:\Users\Your
Name>node linecount.js
Slip 28 A check whether given name is file of directory , if it is file , truncate content after 10 bytes.
var fs=require("fs");
var buf=new Buffer(1024);
fs.open('programming.txt','r+',function(err,fd){
if(err){
return console.error(err);
}
fs.ftruncate(fd,10,function(err){
if(err){ console.log(err);
}
fs.read(fd,buf,0,buf.length,0,function(err,bytes){ if(err){
console.log(err);
}
if(bytes>0){
console.log(buf.slice(0,bytes).toString());
}
fs.close(fd,function(err){
if(err){ console.log(err);
}
});});});});
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: ""
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("CREATE DATABASE hospitaldb", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
var sql = "CREATE TABLE hospital(name VARCHAR(255), contact int(10))";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
var sql = "INSERT INTO hospital (name, contact) VALUES ?";
var values = [
['abc',7545452000],
['def', 9014523600],
['ghi', 1012457800]
];
con.query(sql, [values], function (err, result)
{
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
con.query("SELECT * FROM hospital", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
cheap web hosting|cheap hosting|cheap windows hosting|wordpress hosting|best wordpress hosting
All slip solution display kara
ReplyDeleteNode js che
DeleteMa'am previous practical mai slip number 16 tha aur node js mai slip number 16 nhi hai what to do
ReplyDeleteSlip no 3 and 29 is not working. Showing error
ReplyDeleteSpecify file path correctly
ReplyDeleteits working
ReplyDeleteSend others solved slips
ReplyDeleteSlip no 15???
ReplyDeletesend django slip solution
ReplyDeleteOk thanks for this solution buddy
ReplyDelete