0% found this document useful (0 votes)
25 views9 pages

We Lab (Ans)

Uploaded by

shashipavan5203
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)
25 views9 pages

We Lab (Ans)

Uploaded by

shashipavan5203
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/ 9

//Q-4 : Write a javascript code to determine the length of each string object in

an array of string objects.


function findLength(ar){
const lengths=ar.map(l=>l.length)
console.log("Array of lengths of each string:")
console.log(lengths);
}

const ar=["hello","hi","world","java script"];


findLength(ar)

//Q-5 : Demonstrate how destructuring property is applied on arrays and


objects.
//arrays

let intro=["hello","this","is","java script"]


let [greet,,,name]=intro
console.log(greet)
console.log(name)

let a,b,rest;
[a,b,...rest]=[10,20,30,"hello","world"]
console.log(rest)

function sample(){
return ["This","is","sample","code"]
}
let [result]=sample()
console.log(result)

//objects

let person={name1:"john",age:25}
let {name1}=person
console.log(name1)

let {name1:id,age:age1}=person
console.log(id)
console.log(age1)
//Q-9 : Write a javascript code for combining yield values.
function *gen1(i){
yield i+1;
yield i+2;
}

function *gen2(i){
yield i;
yield * gen1(i)
yield i+4
}
const g=gen2(10)
console.log(g.next().value)
console.log(g.next().value)
console.log(g.next().value)
console.log(g.next().value)

//Q-10 : Illustrate promises with objects


const data = { id: 1, name: 'Data One' };

function fetchData(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id === 1) {
resolve(data);
}else {
reject('Invalid ID');
}
}, 2000);
});
}
//Generating 0 or 1 randomly
const v = Math.floor(Math.random() * 2);
fetchData(v)
.then(data => {
console.log('Data fetched successfully:', data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
//Q-11 : Demonstrate async and await
function fetchData() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Data fetched!');
}, 2000);
});
}

async function getData() {


console.log('Fetching data...');
const result = await fetchData();
console.log(result);
}

getData();

//Q-21 : Create an application to respond with information like path, http


method, protocol, query string, query parameters of client requests.
const express = require("express");
const cookie = require('cookie-parser');
const app = express();

app.use(cookie());

app.get('/great/:theValue', (req, res) => {


res.set({ 'Content-Type': 'text/plain;charset=utf-8' });
let path = req.path;
let protocol = req.protocol;
let params = req.params;
let name = req.query.name;
let msg = Hello ${name}! Request path=${path}, protocol=${protocol},
app=${req.query.app}, and method=${req.method};
res.send(msg);
});

app.listen(2000, () => console.log("App running at port 2000"));


//Q-22 : Design a node.js application to perform RESTful API using Thunder
Client and express js .
const express = require("express")
const app = express()
app.use(express.json())
let students = [
{ id: 1, name: "abc", branch: "ece" },
{ id: 2, name: "pqr", branch: "cse" },
{ id: 3, name: "xyz", branch: "it" }
]

app.get("/students", (req, res) => {


res.send(students)
})

app.post("/students", (req, res) => {


student = {
id: students.length + 1,
name: req.body.name,
branch: req.body.branch
}
students.push(student)
res.send(students)
})

app.put("/students/:id", (req, res) => {


let id = req.params.id
let st = students.find(std => std.id === parseInt(id))
if (!st) {
res.send("student not found")
}
st.branch = req.body.branch
res.send(students)
})

app.delete("/students/:id", (req, res) => {


let id = req.params.id
let st = students.findIndex(std => std.id === parseInt(id))
if (st === -1) {
res.send("student not found")
}
students.splice(st, 1)
res.send(`students with ${id} is deleted`)
})
app.listen(2000, () => {
console.log("server is running on port 2000");
})
//Q-26 : RESTAPI application for performing crud operations using MongoDB,
express js and thunder client
const express = require('express')
const mongoose = require('mongoose');
const app = express()
app.use(express.json())
const Schema = new mongoose.Schema({
id: Number,
name: String,
branch: String,
});
const stds = mongoose.model('std1', Schema);
mongoose.connect('mongodb://localhost:27017/student')

app.get("/students", async (req, res) => {


let stud = await stds.find()
res.json(stud)
})

app.post("/students", async (req, res) => {


const student=new stds({
id:parseInt(req.body.id),
name:req.body.name,
branch:req.body.branch
})
await student.save();
res.send(`student with ${student.id} is added`)
})

app.put("/students/:id",async (req,res)=>{
const sid=parseInt(req.params.id)
const student=await stds.findOneAndUpdate({id:sid},req.body, { new: true })
if(!student)
return res.send(`student with id ${sid} doesn't exists`)
res.send(student)
})

app.delete("/students/:id",async(req,res)=>{
const sid=parseInt(req.params.id)
const student= await stds.findOneAndDelete({id:sid})
if(!student)
return res.send(`student with id ${sid} doesn't exists`)
res.send(`student ${student} is deleted`)
})
app.listen(2000, () => {
console.log("server is running on port 2000");
})
//Q-27 : Create an application to render dynamic content in web applications
(EJS) .
const express = require("express")
const app = express()
app.use(express.json())
app.set("view engine", "ejs");
let students = [
{ id: 1, name: "abc", branch: "ece" },
{ id: 2, name: "pqr", branch: "cse" },
{ id: 3, name: "xyz", branch: "it" }
]
app.get("/", (req, res) => {
res.send("hello world")
})

app.get("/students", (req, res) => {


res.render("students", { students: students })
})

app.get("/students/:id", (req, res) => {


let id = req.params.id
let st = students.find(std => std.id === parseInt(id))
if (!st) {
res.send("student not found")
}
res.render("std", { student: st })
})

app.listen(2000, () => {
console.log("server is running on port 2000");
})

std.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<center>
<table border="1">
<tr style="border: 3px solid black;">
<th>ID</th>
<th>name</th>
<th>branch</th>
</tr>
<tr>
<td>
<%= student.id %>
</td>
<td>
<%= student.name %>
</td>
<td>
<%= student.branch%>
</td>
</tr>
</table>
</center>
</body>

</html>

students.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<center>
<h1>Items</h1>
<table border="1">
<tr style="border: 3px solid black;">
<th>ID</th>
<th>Name</th>
<th>Branch</th>
</tr>
<% students.forEach(std=> { %>
<tr>
<td>
<%= std.id %>
</td>
<td>
<%= std.name %>
</td>
<td>
<%= std.branch %>
</td>
</tr>
<% }); %>
</table>
</center>
</body>
</html>

//Q: write a program to read a file and write into a file using fs module
const fs=require('fs')
fs.readFile("input.txt",(err,data)=>{
if (err) {
console.error('Error reading file:', err);
return;
}
fs.writeFile("output.txt",data,'utf8',(err)=>{
if (err) {
console.error('Error writing to file:', err);
return;
}
console.log('File successfully written')
})
})

//Q: write a program to stream data from one file to another


var fs = require('fs');
var readableStream = fs.createReadStream('input.txt');
var writableStream = fs.createWriteStream('copy.txt');

readableStream.setEncoding('utf8');

readableStream.on('data', function(chunk) {
writableStream.write(chunk);
console.log("successfully copied")
});
//Q:Implement and write the procedure to perform push and pull request
>mkdir dir
>cd dir
>git config --global user.name “<username>”
>git config --global user.email “<user email>”

>git init
>git branch b1
>git checkout b1
>touch file.txt

>git add .
>git commit -m “file created”
>git remote add origin <user github repository url>
>git push origin b1

->To generate pull request


-Go to pull request tab
-click on new pull request
-create pull request

You might also like