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

Backend Lab

The document provides the steps to create a department website using Node.js: 1. Import the Express module and setup a template engine like Pug to render HTML files. 2. Save the Pug template files in a templates folder in the same directory as the JS file. 3. Render the template files and run the server on localhost:4000 to view the website on a browser.

Uploaded by

Hema Senthil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Backend Lab

The document provides the steps to create a department website using Node.js: 1. Import the Express module and setup a template engine like Pug to render HTML files. 2. Save the Pug template files in a templates folder in the same directory as the JS file. 3. Render the template files and run the server on localhost:4000 to view the website on a browser.

Uploaded by

Hema Senthil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Ex no 1.

a Console Application To Generate Welcome & Slice The Arguments

AIM
To create a console application to generate welcome using node js.
PROCEDURE
Step 1 : Take any text editor.
Step 2 : start the program.
Step 3: use console.log to print user enters.
Step 4 : save the file in .js extension.
Step 5 : use node filename.js in cmd to execute the code.
Step 6: enter exit to quit terminal.
PROGRAM
console.log('Hi Hello World! Welcome’);

console.log('Hello World');
console.log(process.argv.slice(2));

OUTPUT

RESULT
Thus the console application to create welcome is executed and the output is displayed.
Ex no 1.b Event Model

AIM
To create a console application to create event model using JS.
PROCEDURE
Step 1 : take any text editor.
Step 2 : import the events package and save it.
Step 3 : initialize event emitters instances.
Step 4 : register the event that you want to do into Myevents.
Step 5 : trigger Myevents, using emit function.
Step 6 : use node filename.js in cmd to execute the code.
Step 7 : enter exit to quit terminal.

PROGRAM
class EventEmitter {
listeners = {}
addListener(eventName, fn) {
this.listeners[eventName] = this.listeners[eventName] || [];
this.listeners[eventName].push(fn);
return this;
}
on(eventName, fn) {
return this.addListener(eventName, fn);
}
once(eventName, fn) {
this.listeners[eventName] = this.listeners[eventName] || [];
const onceWrapper = () => {
fn();
this.off(eventName, onceWrapper);
}
this.listeners[eventName].push(onceWrapper);
return this;
}
off(eventName, fn) {
return this.removeListener(eventName, fn);
}
removeListener (eventName, fn) {
let lis = this.listeners[eventName];
if (!lis) return this;
for(let i = lis.length; i > 0; i--) {
if (lis[i] === fn) {
lis.splice(i,1);
break;
}
}
return this;
}
emit(eventName, ...args) {
let fns = this.listeners[eventName];
if (!fns) return false;
fns.forEach((f) => {
f(...args);
});
return true;
}
listenerCount(eventName) {
let fns = this.listeners[eventName] || [];
return fns.length;
}
rawListeners(eventName) {
return this.listeners[eventName];
}
}
const myEmitter = new EventEmitter();
function c1() {
console.log('an event occurred!');
}
function c2() {
console.log('yet another event occurred!');
}
myEmitter.on('eventOne', c1); // Register for eventOne
myEmitter.on('eventOne', c2); // Register for eventOne
myEmitter.once('eventOnce', () => console.log('eventOnce once fired'));
myEmitter.once('init', () => console.log('init once fired'));
myEmitter.on('status', (code, msg)=> console.log(`Got ${code} and ${msg}`));
myEmitter.emit('eventOne');
myEmitter.emit('eventOnce');
myEmitter.emit('eventOne');
myEmitter.emit('init');
myEmitter.emit('init');
myEmitter.emit('eventOne');
myEmitter.emit('status', 200, 'ok');
console.log(myEmitter.listenerCount('event1'));
console.log(myEmitter.rawListeners('event1'));
class WithTime extends EventEmitter {
execute(asyncFunc, ...args) {
this.emit('begin');
console.time('execute');
this.on('data', (data)=> console.log('got data ', data));
asyncFunc(...args, (err, data) => {
if (err) {
return this.emit('error', err);
}
this.emit('data', data);
console.timeEnd('execute');
this.emit('end');
});
}
}
const withTime = new WithTime();
withTime.on('begin', () => console.log('About to execute'));
withTime.on('end', () => console.log('Done with execute'));
const readFile = (url, cb) => {
fetch(url)
.then((resp) => resp.json()) // Transform the data into json
.then(function(data) {
cb(null, data);
});}
withTime.execute(readFile, 'https://jsonplaceholder.typicode.com/posts/1');
myEmitter.off('eventOne', c1);
myEmitter.off('eventOne', c2);
console.log(myEmitter.listenerCount('eventOne'));
console.log(withTime.rawListeners("begin"));
OUTPUT:

RESULT
Thus the Event model using node js is executed and the output is displayed.
Ex 2 File System Calls
AIM
To create a file system call programs for opening ,closing ,reading and writing files using
node.js
PROCEDURE
Step 1 : open any text editor.
Step 2 : create a text file and type some content in it.
Step 3 : import the fs package into the script.
Step 4 : read the file using readfilesync function.
Step 5 : convert the data into string.
Step 6 : print in console that the code has ended.
Step 7 : use node filename.js in cmd to execute the code.
Step 8 : enter exit to quit terminal.

PROGRAM
Ex3.js
Openfile.js
var fs = require("fs");

// Asynchronous - Opening File


console.log("opening file!");
fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("File open successfully");
Inputfile1.txt
Hello Programmer!!!Learn NodeJS for fun.
OUTPUT
opening file!
File open successfully
Readfile.js
var fs = require("fs");
var buf = new Buffer(1024);

console.log("opening an existing file");


fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("File opened successfully!");
console.log("reading the file");

fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){


if (err){
console.log(err);
}
console.log(bytes + " bytes read");

// Print only read bytes to avoid junk.


if(bytes > 0){
console.log(buf.slice(0, bytes).toString());
}
});
Output:
opening an existing file
File opened successfully!
reading the file
40 bytes read
Hello Programmer!!!Learn NodeJS for fun.
Writefile.js
var fs = require("fs");

console.log("writing into existing file");


fs.writeFile('input.txt', 'Gee', function(err) {
if (err) {
return console.error(err);
}

console.log("Data written successfully!");


console.log("Let's read newly written data");

fs.readFile('input.txt', function (err, data) {


if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
Output:
writing into existing file
Data written successfully!
Let's read newly written data
Asynchronous read: Gee

RESULT

Thus the call back function using Node JS is executed and the output is displayed.
Ex no 3.a JSON TO CSV

AIM
To create a node js application to convert JSON to CSV.
PROCEDURE
Step 1 : open any text editor.
Step 2 : import json2csv module and declare the json details in an array.
Step 3 : by using convert function convert the json array to a csv string.
Step 4 : print the csv string.
Step 5 : use node filename.js in cmd to execute the code.
Step 6 : enter exit to quit terminal.
PROGRAM

const converter = require('json-2-csv')


const todos = [
{
id: 1,
title: 'kamal’,
completed: false
},
{
id: 2,
title: 'vijay’,
completed: false
},
{
id: 3,
title: 'rajni',
completed: false
}
]

converter.json2csv(todos, (err, csv) => {


if (err) {
throw err
}
console.log(csv)
})

OUTPUT
RESULT
Thus a node js application to create json to csv is executed and the output is displayed.
Ex no 3 .b CSV TO JSON

AIM
To create a node js application to convert CSV to JSON.
PROCEDURE
Step 1 : open any text editor.
Step 2 : import csvtojson module.
Step 3 : save the details in a csv file.
Step 4 : read that file and convert csv to json.
Step 5 : use node filename.js in cmd to execute the code.
Step 6 : enter exit to quit terminal.
PROGRAM

const fs = require("fs")
function csvToJson() {
const csv = fs.readFileSync("C:\\Users\\system\\Act.csv")
const array = csv.toString().split("\n")
// first line is list of keys
const keys = array[0].split(';'), res = [];
for (let i = 1; i < array.length; i++) {
// get entries
const entry = array[i].split(';'), obj = {}
// assign keys to values
for (let j = 0; j < keys.length; j++) obj[keys[j]] = entry[j];
res.push(obj)
}
return res;
}
try {
console.log(csvToJson())
} catch (error) {
console.log(error)
}
user.csv

id,name,email,country,age
100,Atta Shah,[email protected],PK,30
101,Alex Jones,[email protected],DE,35
102,Jovan Lee,[email protected],FR,25
103,Greg Hover,[email protected],US,45
OUTPUT

RESULT
Thus a node js application to create csv to json is executed and the output is displayed.
EX NO 4 OPENING OF A FILE READ AND WRITE
A CONTENT TO AND FROM A FILE

AIM
To create a node js program to open a file read and write a content to and from a file.
PROCEDURE
Step 1 : open any text editor.
Step 2 : Import fs module into the script
Step 3 : take a txt file and save some data in it.
Step 4 : by using readfilesync read the data from the user created txt file.
Step 5 : by using writefile write the data into a new txt file.
Step 6 : use node filename.js in cmd to execute the code.
Step 7 : enter exit to quit terminal.
PROGRAM
var fs = require('fs');
fs.readFile('inputfile1.txt', 'utf-8', function(err, data) {
if( !err )
fs.writeFile('writeMe.txt', data, (err)=>{
if( err ) {
throw err;
}
});
else
throw err;
});
Inputfile1.txt

OUTPUT
RESULT
Thus opening a file-reading and writing to and from file is executed and the output is
displayed.
Ex no 5 CREATE A DEPARTMENT WEBSITE
USING NODE JS FRAMEWORK

AIM
To create a department website using node js framework.
PROCEDURE
Step 1 : open any text editor.
Step 2 : import express module into the js file and setup a template engine (pug) to run html
file.
Step 3 : save the pug file in a templates folder under the same directory.
Step 4 : render the file and run on the browser on localhost:4000.
Step 5: use node filename.js in cmd to execute the code.
Step 6 : enter exit to quit terminal.
PROGRAM
Js file
const express = require('express');
const app = express();
app.set('view engine','pug');
app.set('views','./Templates');
app.get('/',function(req,res){
res.render('Example')
})
app.listen(4000,()=>console.log("App Started"));
Example.pug
doctype html
head
title DEPARTMENT PAGE
style.

*{
margin: 0;
padding: 0;
}
.navbar {
display: flex;
align-items: center;
justify-content: center;
position: sticky;
top: 0;
cursor: pointer;
}
.background {
background: black;
background-blend-mode: darken;
background-size: cover;
}
.nav-list {
width: 70%;
display: flex;
align-items: center;
}
.logo {
display: flex;
justify-content: center;
align-items: center;
}
.logo img {
width: 180px;
border-radius: 50px;
}
.nav-list li {
list-style: none;
padding: 26px 30px;
}
.nav-list li a {
text-decoration: none;
color: white;
}
.nav-list li a:hover {
color: grey;
}
.rightnav {
width: 30%;
text-align: right;
}
#search {
padding: 5px;
font-size: 17px;
border: 2px solid grey;
border-radius: 9px;
}
.firstsection {
background-color: green;
height: 400px;
}
.secondsection {
background-color: blue;
height: 400px;
}
.box-main {
display: flex;
justify-content: center;
align-items: center;
color: black;
max-width: 80%;
margin: auto;
height: 80%;
}
.firsthalf {
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
}
.secondhalf {
width: 30%;
}
.secondhalf img {
width: 70%;
border: 4px solid white;
border-radius: 150px;
display: block;
margin: auto;
}
.text-big {
font-family: 'Piazzolla', serif;
font-weight: bold;
font-size: 35px;
}
.text-small {
font-size: 18px;
}
.btn {
padding: 8px 20px;
margin: 7px 0;
border: 2px solid white;
border-radius: 8px;
background: none;
color: white;
cursor: pointer;
}
.btn-sm {
padding: 6px 10px;
vertical-align: middle;
}
.section {
height: 400px;
display: flex;
align-items: center;
justify-content: center;
max-width: 90%;
margin: auto;
}
.section-Left {
flex-direction: row-reverse;
}
.paras {
padding: 0px 65px;
}
.thumbnail img {
width: 250px;
border: 2px solid black;
border-radius: 26px;
margin-top: 19px;
}
.center {
text-align: center;
}
.text-footer {
text-align: center;
padding: 30px 0;
font-family: 'Ubuntu', sans-serif;
display: flex;
justify-content: center;
color: white;
}
nav.navbar.background
ul.nav-list
li
a(href='#web') COMPUTER SCIENCE DEPARTMENT
li
a(href='#web') About us
li
a(href='#program') vision
li
a(href='#course') mission
.rightNav
input#search(type='text' name='search')
button.btn.btn-sm Search
section.firstsection
.box-main
.firstHalf
h1#web.text-big About us
p.text-small
| Welcome to the Computer Science and Engineering Department at the B.S.Abdur Rahman Crescent
Institute of Science and Technology
| Our exciting, rich and dynamic field has been pushing the boundaries of what is possible through the
discovery of new ideas and the building of innovative systems and tools that have changed our lives.
| The Department of Computer Science & Engineering has been in existence since 1990 (30 Years of
Excellence), Given the high demand for Computer Science professionals from the industry, the department
offers four undergraduate programs namely B.Tech. Computer Science and Engineering, B.Tech. Artificial
Intelligence & Data Science, B.Tech. CSE (Cyber Security), and B.Tech. CSE (Internet of Things).
section.secondsection
.box-main
.firstHalf
h1#program.text-big VISION
p.text-small
| The vision of the Department of Computer Science and engineering is to impart quality education,
inculcate professionalism and enhance the problem solving skills of the students in the domain of
Computer Science and Engineering with a focus to make them industry ready, involve in possible areas of
research, to pursue and have continual professional growth.
.paras
h1.sectionTag.text-big MISSION
p.sectionSubTag.text-small
| To equip the students with strong fundamental concepts, analytical capability, programming and
problem solving skills.
| To create an academic environment conducive for higher learning through faculty training, self
learning, sound academic practices and research endeavors.
footer.background
p.text-footer
| Copyright &copy;-All rights are reserved
OUTPUT
RESULT
thus the creation of department website node js framework is executed and the output is
displayed.
Ex no 6 APPLICATION USING ROUTING

AIM
To create a express js application using routing module.
PROCEDURE
Step 1 : open any text editor.
Step 2 : import express & fs modules into the js file.
Step 3 : define the ‘/ ‘ for the routing.
Step 4 : save the file and run on the browser on localhost:3000.
Step 5 : use ‘/ ’ after the ip and the port number and say where the routing to be done.
Step 6: use node filename.js in cmd to execute the code.
Step 7 : enter exit to quit terminal.
PROGRAM
App.js
const express = require('express')
const fs = require('fs')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('hello world')
})
app.get('/about', (req, res) => {
res.send('this is about page ')
})
app.get('/todos', (req, res) => {
fs.readFile('./todos.json', 'utf-8', (err, data) => {
let todos = JSON.parse(data)
res.send(todos)
})
})
app.get('/todos/:id', (req, res) => {
fs.readFile('./todos.json', 'utf-8', (err, data) => {
let todos = JSON.parse(data)
let index = todos.findIndex(todo => {
return todo.id == req.params.id
})
let todo = todos[index]
res.send(todo)
})
})
app.listen(port, () => {
console.log('app listen to port', port)
})

/todos
[
{
"id": 1,
"task": "Learn new things"
},
{
"id": 2,
"task": "Explore ExpressJS"
},
{
"id": 3,
"task": "Create a request response app"
}]
OUTPUT
RESULT
Thus the creation of Express JS Application using routing is executed and the output is
displayed.

You might also like