0% found this document useful (0 votes)
4 views

FST Lab Programs

The document outlines various exercises demonstrating React components, Redux applications, React routing, and Node.js file handling. Each exercise includes code snippets for creating a React component lifecycle demo, a calculator app, a Redux counter, a routing website, and Node.js applications for data I/O and file system access. The document serves as a comprehensive guide for practical implementations of these technologies.

Uploaded by

22501a12a4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

FST Lab Programs

The document outlines various exercises demonstrating React components, Redux applications, React routing, and Node.js file handling. Each exercise includes code snippets for creating a React component lifecycle demo, a calculator app, a Redux counter, a routing website, and Node.js applications for data I/O and file system access. The document serves as a comprehensive guide for practical implementations of these technologies.

Uploaded by

22501a12a4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

EXERCISE – 1

AIM: Demonstrate React Component Life cycle

index.js
import React, { Component } from 'react';
import { render } from 'react-dom';

class LifeCycleDemoComponent extends Component {


constructor(props) {
super(props);
}

componentDidMount() {
console.log('componentDidMount');
}

componentDidUpdate() {
console.log('componentDidUpdate');
}

componentWillUnmount() {
console.log('componentWillUnmount');
}

render() {
return <p>{this.props.num}</p>
}
}

class App extends Component {


constructor() {
super();
this.state = {
num: 0,
show: false
}
}

render() {
return (
<>
<button onClick={() => this.setState({ num: this.state.num + 1 })}>Add One</button>
<button onClick={() => this.setState({show: !this.state.show})}>Toggle</button>
{this.state.show && <LifeCycleDemoComponent num={this.state.num} />}
</>);
}
}

render(<App />, document.getElementById('root'));

Output:
EXERCISE - 2

AIM: Develop a Calculator React Application

index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

const rootElement = document.getElementById("root");


ReactDOM.render(
<App />,
rootElement
);

App.js
import React, { Component } from 'react';
import './styles.css';
import ResultComponent from './components/ResultComponent';
import KeyPadComponent from './components/KeyPadComponent';

class App extends Component {


state = {
result: ""
}

onClick = button => {


if(button === "=") {
this.calculate();
}

else if(button === "C") {


this.reset();
}

else if(button === "del") {


this.backspace();
}

else {
this.setState({
result: this.state.result + button
})
}
};

calculate = () => {
var checkResult = ''
checkResult = this.state.result;

try {
this.setState({
result: (eval(checkResult)) })
}
catch(e) {
this.setState({
result: "error"
})
}
};

reset = () => {
this.setState({
result: ""
})
};

backspace = () => {
this.setState({
result: this.state.result.slice(0, -1)
})
};

render() {
return (
<div>
<div className="calculator-body">
<h1>Simple Calculator</h1>
<ResultComponent result={this.state.result} />
<KeyPadComponent onClick={this.onClick} />
</div>
</div>
)
}
}

export default App;


ResultComponent.js
import React, { Component } from 'react';

class ResultComponent extends Component {


render() {
let { result } = this.props;
return (
<div className="result">
<p>{ result }</p>
</div>
)
}
}
export default ResultComponent;

KeyPadComponent.js
import React, { Component } from 'react';

class KeyPadComponent extends Component {


render() {
return (
<div className="button">

<button name="(" onClick={e => this.props.onClick(e.target.name)}>(</button>


<button name="del" onClick={e => this.props.onClick(e.target.name)}>CE</button>
<button name=")" onClick={e => this.props.onClick(e.target.name)}>)</button>
<button name="C"onClick={e=>this.props.onClick(e.target.name)}>C</button><br/>

<button name="1" onClick={e => this.props.onClick(e.target.name)}>1</button>


<button name="2" onClick={e => this.props.onClick(e.target.name)}>2</button>
<button name="3" onClick={e => this.props.onClick(e.target.name)}>3</button>
<button name="+" onClick={e => this.props.onClick("+")}>+</button><br/>

<button name="4" onClick={e => this.props.onClick(e.target.name)}>4</button>


<button name="5" onClick={e => this.props.onClick(e.target.name)}>5</button>
<button name="6" onClick={e => this.props.onClick(e.target.name)}>6</button>
<button name="-" onClick={e => this.props.onClick(e.target.name)}>-</button><br/>

<button name="7" onClick={e => this.props.onClick(e.target.name)}>7</button>


<button name="8" onClick={e => this.props.onClick(e.target.name)}>8</button>
<button name="9" onClick={e => this.props.onClick(e.target.name)}>9</button>
<button name="*" onClick={e =>this.props.onClick(e.target.name)}>x</button><br/>

<button name="." onClick={e => this.props.onClick(e.target.name)}>.</button>


<button name="0" onClick={e => this.props.onClick(e.target.name)}>0</button>
<button name="=" onClick={e => this.props.onClick(e.target.name)}>=</button>
<button name="/" onClick={e =>this.props.onClick(e.target.name)}>÷</button><br/>
</div>
)
}
}
export default KeyPadComponent;

Output:
EXERCISE-3

AIM: Develop a Redux application

index.js
import React from "react";
import {createRoot} from 'react-dom/client';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import App from './App';

const initialState = {
count: 0
};

function reducer(state = initialState, action) {


switch(action.type)
{
case 'INCREMENT': return { count: state.count + 1 };
case 'DECREMENT': return { count: state.count - 1 };
default: return state;
}
}

const store = createStore(reducer);


const root = createRoot(document.getElementById('root'));
root.render(<Provider store={store}>
<App />
</Provider>);

App.js
import React from 'react';
import { connect } from 'react-redux';

function Counter(props) {
return (
<div>
<h1>Counter: {props.count}</h1>
<button onClick={props.increment}>Increment</button>
<button onClick={props.decrement}>Decrement</button>
</div>
);
}
function mapStateToProps(state) {
return {
count: state.count };
}

function mapDispatchToProps(dispatch) {
return {
increment: () => dispatch({ type: 'INCREMENT' }),
decrement: () => dispatch({ type: 'DECREMENT' }) };
}

export default connect(mapStateToProps, mapDispatchToProps)(Counter);

Output:
EXERCISE - 4

AIM: Develop Website demonstrate React Routing

Header.js
import React from 'react';
import { Link, Outlet} from 'react-router-dom';
const Header = () => { return (<nav>
<Link to="home">Home</Link>
<Link to="about"> About Us </Link>
<Link to="contact"> Contact Us </Link>
<Outlet/>
</nav>)
}
export default Header;

About.js
const About = () => {
return <>
<h2> Inside About Us</h2>
</>
}
export default About;

Contact.js
const ContactUs = () => {
return <>
<h2> Inside ContactUs</h2>
</>
}
export default ContactUs;

Home.js
const Home = () => {
return <>
<h2> Inside home</h2>
</>
}
export default Home;

index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import {BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Header from './components/Header'; import Home from
'./components/Home'; import About from './components/About';
import ContactUs from './components/Contact';

class RoutingDemo extends React.Component{


render(){ return( <Router>
<Routes>
<Route path="/" element={<Header />}>
<Route index element={<Home />}/>
<Route path="home" element={<Home />}/>
<Route path="about" element={<About />}/>
<Route path="contact" element={<ContactUs />}/>
</Route>
</Routes>
</Router>
)
}
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<RoutingDemo />
);

Output:
EXERCISE-5
Aim: Develop a Node.js application demonstrating handling data I/O (Buffer,
Stream, Zlib modules)
buffer.js
buf = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
buf[i] = i + 97;
}
console.log( buf.toString('ascii'));
console.log( buf.toString('ascii',0,5));
console.log( buf.toString('utf8',0,5));
console.log( buf.toString(undefined,0,5));
var buffer1 = new Buffer('Tutorials Point ');
var buffer2 = new Buffer('Simply Easy Learning');
var buffer3 = Buffer.concat([buffer1,buffer2]);
console.log("concatenated content: " + buffer3.toString());
var b1 = buffer1.slice(0,9);
console.log("sliced content: " + b1.toString());
console.log("buffer length: " + buffer1.length);
var json = buf.toJSON(buffer2);
console.log(json);
OUTPUT:
Streams:
WriteStream.js
var fs = require('fs');
var grains = ['wheat', 'rice', 'oats'];
var options = { encoding: 'utf8', flag: 'w' };
var fileWriteStream = fs.createWriteStream("grains.txt", options);
fileWriteStream.on("close", function(){
console.log("File Closed.");
});
while (grains.length){
var data = grains.pop() + " ";
fileWriteStream.write(data);
console.log("Wrote: %s", data);
}
fileWriteStream.end();
var options = { encoding: 'utf8', flag: 'r' };
var fileReadStream = fs.createReadStream("grains.txt", options);
fileReadStream.on('data', function(chunk) {
console.log('Grains: %s', chunk);
console.log('Read %d bytes of data.', chunk.length);
});
OUTPUT :
vowels_count.js
const fs = require('fs');
function countChars(filename) {
const vowels = 'aeiouAEIOU';
let vowelCount = 0;
let consonantCount = 0;
let digitCount = 0;
let specialCharCount = 0;
const stream = fs.createReadStream(filename, { encoding: 'utf8' });
stream.on('data', (data) => {
for (const char of data) {
if (char.match(/[a-zA-Z]/)) {
if (vowels.includes(char)) {
vowelCount++;
} else {
consonantCount++;
}
} else if (char.match(/\d/)) {
digitCount++;
} else if (char.match(/\S/)) {
specialCharCount++;
}
}
});
stream.on('end', () => {
console.log(`Vowels: ${vowelCount}`);
console.log(`Consonants: ${consonantCount}`);
console.log(`Digits: ${digitCount}`);
console.log(`Special Characters: ${specialCharCount}`);
});
stream.on('error', (err) => {
console.error(`Error reading file: ${err}`);
});
}

//reading file from user


const file = process.argv[2];
if (file) {
countChars(file);
} else {
console.error('Please provide a file name as an argument.');
}
OUTPUT :

countLinesWordsChars.js
const fs = require('fs');
const countLinesWordsChars = (file) => {
let lines = 0;
let words = 0;
let chars = 0;
const stream = fs.createReadStream(file, { encoding: 'utf8' });
stream.on('data', (data) => {
lines += data.split('\n').length;
words += data.split(/\s+/).filter(Boolean).length;
chars += data.length;
});
stream.on('end', () => {
console.log(`Number of lines: ${lines}`);
console.log(`Number of words: ${words}`);
console.log(`Number of characters: ${chars}`);
});
stream.on('error', (err) => {
console.error(`Error reading file: ${err}`);
});
};
countLinesWordsChars('grains.txt');
OUTPUT :

pipe.js
var fs = require("fs");
// Create a readable stream
var readerStream = fs.createReadStream('grains.txt');
// Create a writable stream
var writerStream = fs.createWriteStream('c.txt');
// Pipe the read and write operations
// read input.txt and write data to output.txt
readerStream.pipe(writerStream);
console.log("Program Ended");
OUTPUT :
zlib.js
var fs = require("fs");
var zlib = require('zlib');

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


fs.createReadStream('c.txt')
.pipe(zlib.createGzip())
.pipe(fs.createWriteStream('c.txt.gz'));
console.log("File Compressed.");

fs.createReadStream('c.txt.gz')
.pipe(zlib.createGunzip())
.pipe(fs.createWriteStream('c.txt'));
console.log("File Decompressed.");

OUTPUT :
EXERCISE – 6
Aim: Demonstrate accessing File system from Node.js application
samplefile.js
var fs = require("fs");
console.log("Going to get file info!");
fs.stat('input.txt', function (err, stats) {
if (err) { return console.error(err); }
console.log(stats);
console.log("Got file info successfully!");
console.log("isFile ? " + stats.isFile());
console.log("isDirectory ? " + stats.isDirectory());
});
OUTPUT :

WriteS.js
var fs = require('fs');
var veggieTray = ['carrots', 'celery', 'olives'];
fd = fs.openSync('veggie.txt', 'w');
while (veggieTray.length){
veggie = veggieTray.pop() + " ";
var bytes = fs.writeSync(fd, veggie, null, null);
console.log("Wrote %s %dbytes", veggie, bytes);
}
fs.closeSync(fd);
fd = fs.openSync('veggie.txt', 'r');
var veggies = "";
do {
var buf = new Buffer(5);
buf.fill();
var bytes = fs.readSync(fd, buf, null, 5);
console.log("read %dbytes", bytes);
veggies += buf.toString();
} while (bytes > 0);
fs.closeSync(fd);
console.log("Veg g (to get output shown) ies: " + veggies);
OUTPUT :

WriteAS.js
var fs = require('fs');
var fac = {
Name: "chp",
Branch: "IT",
Experience: 10
};
var configTxt = JSON.stringify(fac);
var options = {encoding:'utf8', flag:'w'};
fs.writeFile('config.txt', configTxt, options,
function(err){
if (err){
console.log("Faculty details Write Failed.");
} else {
console.log("Faculty details Saved.");
}} );
options = {encoding:'utf8', flag:'r'};
fs.readFile('config.txt', options, function(err, data){
if (err){
console.log("Failed to open Faculty File.");
} else {
console.log("Faculty details:");
var fac = JSON.parse(data);
console.log("Name: " + fac.Name);
console.log("Branch: " + fac.Branch);
console.log("Experience: " + fac.Experience);

}
});
OUTPUT:

List.js
var fs = require('fs');
var Path = require('path');
function WalkDirs(dirPath){
console.log(dirPath);
fs.readdir(dirPath, function(err, entries){
for (var idx in entries){
var fullPath = Path.join(dirPath, entries[idx]);
(function(fullPath){
fs.stat(fullPath, function (err, stats){
if (stats.isFile()){
console.log(fullPath);
} else if (stats.isDirectory()){
WalkDirs(fullPath); }
});
})(fullPath);}
});
}

WalkDirs("../Files");
OUTPUT:
file_stats.js
var fs = require('fs');
fs.stat('file_stats.js', function (err, stats) {
if (!err){
console.log('stats: ' + JSON.stringify(stats, null, ' '));
console.log(stats.isFile() ? "Is a File" : "Is not a File");
console.log(stats.isDirectory() ? "Is a Folder" : "Is not a Folder");
console.log(stats.isSocket() ? "Is a Socket" : "Is not a Socket");
stats.isDirectory();
stats.isBlockDevice();
stats.isCharacterDevice();
//stats.isSymbolicLink(); //only lstat
stats.isFIFO();
stats.isSocket();
}
});
OUTPUT:

Duplex.js
var stream = require('stream');
var util = require('util');
util.inherits(Duplexer, stream.Duplex);
function Duplexer(opt) {
stream.Duplex.call(this, opt);
this.data = [];
}
Duplexer.prototype._read = function readItem(size) {
var chunk = this.data.shift();
if (chunk == "stop"){
this.push(null);
} else {
if(chunk){
this.push(chunk);
} else {
setTimeout(readItem.bind(this), 500, size);}} };
Duplexer.prototype._write = function(data, encoding, callback) {
this.data.push(data);
callback();};
var d = new Duplexer();
d.on('data', function(chunk){
console.log('read: ', chunk.toString()); });
d.on('end', function(){
console.log('Message Complete');
});
d.write("I think, ");
d.write("therefore ");
d.write("I am.");
d.write("Rene Descartes");
d.write("stop");
OUTPUT:
EXERCISE - 7
Aim : Demonstrate Express Routing.
basic_express.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Welcome to Express js!');
});
var server = app.listen(8000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
OUTPUT :

routing_example.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
console.log("Got a GET request for the homepage");
res.send('Welcome to Express js routing !');
})
app.get('/enrolled_student', function (req, res) {
console.log("Got a GET request for /enrolled_student");
res.send('I am an enrolled student.');
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
app.get('/ab*cd', function(req, res) {
console.log("Got a GET request for /ab*cd");
res.send('Pattern Matched.');
})
var server = app.listen(8000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
OUTPUT :

route_params.js
const express = require('express');
const app = express();
const users = [ { id: 1, name: 'Gr' },{ id: 2, name: 'vr' },{ id: 3, name: 'pnr' }, ];
app.get('/users/:id', (req, res) => {
const id = parseInt(req.params.id);
const user = users.find(user => user.id === id);
if (!user) {
return res.status(404).send('User not found');
}
return res.send(user);
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
OUTPUT:
EXERCISE – 8
Aim : Demonstrate Express.js Authentication
basic_auth.js
const express = require('express');
const app = express();
const basicAuth = require('express-basic-auth');
const auth = basicAuth({
users: { 'testuser': 'tes' },
challenge: true });
app.get('/library', (req, res) => {
res.send('Welcome to the library.');
});
app.get('/restricted', auth, (req, res) => {
res.send('Welcome to the restricted section.');
});
app.listen(80, () => {
console.log('Server running on port 3000');
});
OUTPUT :
Page_auth.js
var express = require('express');
var crypto = require('crypto');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
function hashPW(pwd) {
return crypto.createHash('sha256').update(pwd).digest('base64').toString();
}
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser('MAGICString'));
app.use(session({
secret: 'MAGICString',
resave: true,
saveUninitialized: true
}));
app.get('/restricted', function(req, res) {
if (req.session.user) {
res.send('<h2>' + req.session.success + '</h2>' +
'<p>You have Entered the restricted section<p><br>' +
' <a href="/logout">logout</a>'); }
else {
req.session.error = 'Access denied!';
res.redirect('/login'); } });
app.get('/logout', function(req, res) {
req.session.destroy(function() {
res.redirect('/login'); });
});
app.get('/login', function(req, res) {
var response = '<form method="POST">' +'Username: <input type="text"
name="username"><br>' +
'Password: <input type="password" name="password"><br>' +
'<input type="submit" value="Submit"></form>';
if (req.session.user) {
res.redirect('/restricted');}
else if (req.session.error) {
response += '<h2>' + req.session.error + '<h2>'; }
res.type('html');
res.send(response);
});
app.post('/login', function(req, res) {
var user = { name: req.body.username, password: hashPW('myPass') };
if (user.password === hashPW(req.body.password.toString())) {
req.session.regenerate(function() {
req.session.user = user;
req.session.success = 'Authenticated as ' + user.name;
res.redirect('/restricted'); }); }
else {
req.session.regenerate(function() {
req.session.error = 'Authentication failed.';
res.redirect('/restricted'); });
res.redirect('/login'); }
});
app.listen(80);
OUTPUT:
EXERCISE – 9
Aim: Demonstrate Manipulating MongoDB Documents from Node.js
manipulating.js
const { MongoClient } = require('mongodb');
const uri = 'mongodb://127.0.0.1:27017'
console.log("Before connecting to database");
MongoClient.connect(uri)
.then(client => { console.log("Connected to database!");
console.log("Database name:", client.db().databaseName);
//creating a database
var dbo = client.db("mydb3");
console.log("Database name:", dbo.databaseName);
//creating a collection "fac"
dbo.createCollection("fac")
.then(() => {
//inserting document
return dbo.collection("fac").insertOne({ name: "chp", branch: "it", sal: 10000,
domain: ["bda", "ml"], date: Date() }); })
.then(() => {
return dbo.collection("fac").insertMany([
{ name: "gr", branch: "it", sal: 20000, domain: ["wt", "java"], date: Date() },
{ name: "vr", branch: "cse", sal: 30000, domain: ["ml", "react"], date: Date() }
]) })
.then(() => {
// updating document
return dbo.collection("fac").updateOne( { name: "chp" }, { $set: { sal: 25000 } } );
})
.then(() => {
// retrieving updated document
return dbo.collection("fac").find().toArray(); })
.then(result => {
console.log("Updated document:", result);
})
.then(() => { // deleting documents with domain as ml
return dbo.collection("fac").deleteMany({ domain: "ml" });
})
.then(() => { // retrieving updated document
return dbo.collection("fac").find().toArray();
})
.then(result => { console.log("Updated document:", result);
client.close();
})
.catch(err => { console.log("Error performing operation:", err); });
})
.catch(err => { console.log("Error connecting to database:", err);
});
OUTPUT:
EXERCISE – 10
Aim: Demonstrate Accessing MongoDB from Node.js.
accessing.js
const { MongoClient } = require('mongodb');
const uri = 'mongodb://127.0.0.1:27017';
console.log("Before connecting to database");
MongoClient.connect(uri)
.then(client => {
console.log("Connected to database!");
console.log("Database name:", client.db().databaseName);
//creating a database
var dbo = client.db("mydb5");
console.log("Database name:", dbo.databaseName);
dbo.createCollection("fac")
.then(() => return dbo.collection("fac").insertOne({name: "chp", branch: "it", sal: 10000,
domain: ["bda", "ml"], date: Date() });
})
.then(() => {
return dbo.collection("fac").insertMany([
{ name: "gr", branch: "it", sal: 20000, domain: ["wt", "java"], date: Date() },
{ name: "vr", branch: "cse", sal: 30000, domain: ["ml", "react"], date: Date() } ])
})
.then(() => return dbo.collection("fac").find().toArray();
})
.then(result => { console.log("Updated document:", result);
client.close();
})
.catch(err => { console.log("Error performing operation:", err);
});
})
.catch(err => console.log("Error connecting to database:", err);
});
OUTPUT:

You might also like