0% found this document useful (0 votes)
2 views17 pages

Nodejs Lab Observation

The document outlines a series of JavaScript and Node.js experiments, ranging from basic concepts like variables and functions to more advanced topics such as Promises, Express.js, and REST APIs. Each experiment includes code snippets and instructions for execution, covering essential programming techniques and web development practices. The content is structured in a sequential manner, making it suitable for learners to progressively build their skills in JavaScript and Node.js.
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)
2 views17 pages

Nodejs Lab Observation

The document outlines a series of JavaScript and Node.js experiments, ranging from basic concepts like variables and functions to more advanced topics such as Promises, Express.js, and REST APIs. Each experiment includes code snippets and instructions for execution, covering essential programming techniques and web development practices. The content is structured in a sequential manner, making it suitable for learners to progressively build their skills in JavaScript and Node.js.
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/ 17

JavaScript Experiments (1–30)

1. Hello World in JavaScript


Standalone: Run this file with a browser (via an HTML file) or Node.js.

// File: hello.js
console.log("Hello World");

2. Variables & Data Types

// File: variables.js
let name = "Alice";
const age = 30;
var isStudent = false;

console.log("Name:", name);
console.log("Age:", age);
console.log("Is Student:", isStudent);
console.log("Type of name:", typeof name);
console.log("Type of age:", typeof age);
console.log("Type of isStudent:", typeof isStudent);

3. Operators and Expressions

// File: operators.js
let a = 10, b = 5;
console.log("Addition:", a + b);
console.log("Subtraction:", a - b);
console.log("Multiplication:", a * b);
console.log("Division:", a / b);
console.log("Is a greater than b?", a > b);

4. Conditional Statements

// File: conditions.js
let score = 85;
if (score >= 90) {
console.log("Grade A");
} else if (score >= 80) {
console.log("Grade B");
} else {
console.log("Grade C");
}

switch(score) {
case 85:
console.log("Exactly 85!");
break;
default:
console.log("Score not 85");
}
5. Loops and Iteration

// File: loops.js
const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log("For loop:", numbers[i]);
}

let i = 0;
while (i < numbers.length) {
console.log("While loop:", numbers[i]);
i++;
}

6. Function Declarations & Expressions

// File: functions.js
// Function Declaration
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice"));

// Function Expression
const square = function(num) {
return num * num;
};
console.log("Square of 5:", square(5));

7. Arrow Functions (ES6)

// File: arrowFunctions.js
const add = (x, y) => x + y;
console.log("Sum:", add(10, 15));

8. Working with Arrays

// File: arrays.js
let fruits = ["apple", "banana", "orange"];
fruits.push("mango");
console.log("Fruits:", fruits);
console.log("First fruit:", fruits[0]);

9. Array Methods: Map, Filter, and Reduce


// File: arrayMethods.js

let numbers = [1, 2, 3, 4, 5];


const doubled = numbers.map(num => num * 2);
console.log("Doubled:", doubled);
const evens = numbers.filter(num => num % 2 === 0);
console.log("Evens:", evens);
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log("Sum:", sum);
10. Objects and Object Literals

// File: objects.js
const person = {
name: "Alice",
age: 30,
greet: function() { return "Hi, I'm " + this.name; }
};
console.log(person.greet());

11. DOM Manipulation


Save the following as an HTML file and open it in your browser.

<!-- File: dom-manipulation.html -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM Manipulation</title>
</head>
<body>
<div id="content">Old Content</div>
<script>
const contentDiv = document.getElementById("content");
contentDiv.innerHTML = "New Content set by JavaScript!";
</script>
</body>
</html>

12. Event Handling


Save this as an HTML file.

<!-- File: event-handling.html -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Event Handling</title>
</head>
<body>
<button id="myButton">Click Me</button>
<script>
document.getElementById("myButton").addEventListener("click",
function() {
alert("Button was clicked!");
});
</script>
</body>
</html>
13. Form Handling & Validation
Save this as an HTML file.

<!-- File: form-validation.html -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Validation</title>
</head>
<body>
<form id="myForm">
<input type="text" id="username" placeholder="Enter username"
required>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("myForm").addEventListener("submit",
function(e) {
e.preventDefault();
const username = document.getElementById("username").value;
if (username.trim() === "") {
alert("Username cannot be empty!");
} else {
alert("Form submitted with username: " + username);
}
});
</script>
</body>
</html>

14. JSON Parsing and Stringifying

// File: jsonExample.js
const obj = { name: "Alice", age: 30 };
const jsonStr = JSON.stringify(obj);
console.log("JSON String:", jsonStr);

const parsedObj = JSON.parse(jsonStr);


console.log("Parsed Object:", parsedObj);

15. Callbacks in JavaScript

// File: callbacks.js
function doTask(callback) {
console.log("Task started...");
setTimeout(() => {
console.log("Task completed!");
callback();
}, 1000);
}

doTask(() => {
console.log("Callback executed after task.");
});
16. Promises and Chaining

// File: promises.js
const promiseExample = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise resolved!");
}, 1000);
});

promiseExample
.then(result => {
console.log(result);
return "Next value";
})
.then(next => {
console.log(next);
})
.catch(error => {
console.error("Error:", error);
});

17. Async/Await

// File: asyncAwait.js
async function fetchData() {
try {
const response = await
fetch("https://jsonplaceholder.typicode.com/todos/1");
const data = await response.json();
console.log("Data:", data);
} catch (error) {
console.error("Error fetching data:", error);
}
}
fetchData();

18. Error Handling with Try/Catch

// File: errorHandling.js
try {
// This will throw an error because the function is not defined
let result = nonExistentFunction();
} catch (error) {
console.error("Caught an error:", error.message);
} finally {
console.log("Cleanup if necessary.");
}
19. Closures in JavaScript

// File: closures.js
function outer() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = outer();
console.log("Counter:", counter()); // 1
console.log("Counter:", counter()); // 2

20. Immediately Invoked Function Expressions (IIFE)

// File: iife.js
(function() {
console.log("IIFE executed immediately!");
})();

21. Module System (ES6 Modules)


Note: Save these as two separate files and run with a module-supporting environment (or
bundler).
o File: math.js
// File: math.js

export function add(a, b) {


return a + b;
}

o File: main.js
// File: main.js

import { add } from './math.js';


console.log("Addition:", add(5, 7));

22. Working with LocalStorage


Save as an HTML file with embedded script.

<!-- File: localStorage.html -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LocalStorage Example</title>
</head>
<body>
<script>
localStorage.setItem("username", "Alice");
console.log("Stored username:", localStorage.getItem("username"));
localStorage.removeItem("username");
</script>
</body>
</html>

23. SessionStorage Example


Save as an HTML file.

<!-- File: sessionStorage.html -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SessionStorage Example</title>
</head>
<body>
<script>
sessionStorage.setItem("sessionID", "ABC123");
console.log("Session ID:", sessionStorage.getItem("sessionID"));
sessionStorage.removeItem("sessionID");
</script>
</body>
</html>

24. Fetch API for HTTP Requests

// File: fetchApi.js
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => console.log("Post data:", data))
.catch(error => console.error("Error:", error));

25. AJAX with XMLHttpRequest

// File: ajax.js
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);
xhr.onload = function() {
if (xhr.status === 200) {
console.log("AJAX response:", xhr.responseText);
}
};
xhr.send();

26. Prototype and Inheritance

// File: prototypes.js
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + " makes a noise.");
};

function Dog(name) {
Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.speak = function() {
console.log(this.name + " barks.");
};

const dog = new Dog("Buddy");


dog.speak();

27. Class-based Syntax (ES6)

// File: classes.js
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hi, I'm ${this.name}`;
}
}
const person1 = new Person("Alice", 30);
console.log(person1.greet());

28. Recursion in JavaScript

// File: recursion.js
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
console.log("Factorial of 5:", factorial(5));

29. Debouncing and Throttling Techniques

// File: debounce.js
function debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
}

window.addEventListener('resize', debounce(() => {


console.log("Window resized!");
}, 500));
30. Regular Expressions

// File: regex.js
function validateEmail(email) {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
console.log("Valid email:", validateEmail("[email protected]"));
console.log("Invalid email:", validateEmail("[email protected]"));

Node.js Experiments (31–50)


31. Basic Node.js Script

// File: hello-node.js
console.log("Hello from Node.js");

Run with: node hello-node.js

32. File System Module – Reading Files


Ensure there is a file named example.txt in the same directory.

// File: readFile.js
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) return console.error(err);
console.log("File content:", data);
});

33. File System Module – Writing Files

// File: writeFile.js
const fs = require('fs');
const content = "Hello, this is a test file.";
fs.writeFile('output.txt', content, err => {
if (err) return console.error(err);
console.log("File written successfully.");
});

34. EventEmitter Basics

// File: eventEmitter.js
const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('greet', () => {
console.log("Hello Event!");
});

emitter.emit('greet');
35. Building a Simple HTTP Server

// File: httpServer.js
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("Hello World from Node.js HTTP server!");
});
server.listen(3000, () => {
console.log("Server listening on port 3000");
});

36. Routing with HTTP Module

// File: httpRouting.js
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("Welcome to the homepage!");
} else if (req.url === '/about') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("About us page");
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end("404 Not Found");
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});

37. Introduction to Express.js


Ensure Express is installed (npm install express).

// File: expressIntro.js
const express = require('express');
const app = express();

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


res.send("Hello from Express!");
});

app.listen(3000, () => {
console.log("Express server listening on port 3000");
});
38. Express Middleware

// File: expressMiddleware.js
const express = require('express');
const app = express();

// Custom middleware to log each request


app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});

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


res.send("Middleware example with Express.");
});

app.listen(3000, () => {
console.log("Server running on port 3000");
});

39. REST API – GET Endpoint

// File: apiGet.js
const express = require('express');
const app = express();

app.get('/api/data', (req, res) => {


res.json({ message: "Data fetched successfully", data: [1, 2, 3, 4,
5] });
});

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

40. REST API – POST Endpoint

// File: apiPost.js
const express = require('express');
const app = express();
app.use(express.json());

app.post('/api/data', (req, res) => {


const receivedData = req.body;
res.json({ message: "Data received successfully", data: receivedData
});
});

app.listen(3000, () => {
console.log("API server running on port 3000");
});
41. CRUD Operations with Express

// File: crudExpress.js
const express = require('express');
const app = express();
app.use(express.json());

let items = []; // In-memory data store

// Create
app.post('/api/items', (req, res) => {
const item = { id: items.length + 1, name: req.body.name };
items.push(item);
res.json(item);
});

// Read
app.get('/api/items', (req, res) => {
res.json(items);
});

// Update
app.put('/api/items/:id', (req, res) => {
const id = parseInt(req.params.id);
let item = items.find(i => i.id === id);
if (item) {
item.name = req.body.name;
res.json(item);
} else {
res.status(404).json({ message: "Item not found" });
}
});

// Delete
app.delete('/api/items/:id', (req, res) => {
const id = parseInt(req.params.id);
items = items.filter(i => i.id !== id);
res.json({ message: "Item deleted" });
});

app.listen(3000, () => {
console.log("CRUD API server running on port 3000");
});

42. Template Engines with Express (Using EJS)


Make sure to install EJS (npm install ejs). Create the file views/index.ejs as
shown below.
o File: expressEJS.js

// File: expressEJS.js
const express = require('express');
const app = express();

app.set('view engine', 'ejs');


app.get('/', (req, res) => {
res.render('index', { title: "EJS Example", message: "Hello
from EJS" });
});

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

o File: views/index.ejs

<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1><%= message %></h1>
</body>
</html>

43. Implementing JWT Authentication


Install jsonwebtoken via npm install jsonwebtoken.

// File: jwtAuth.js
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();

app.use(express.json());
const secretKey = "mySecretKey";

// Login route to generate token


app.post('/login', (req, res) => {
// Dummy user for demonstration; use real authentication in practice.
const user = { id: 1, username: req.body.username };
const token = jwt.sign(user, secretKey, { expiresIn: '1h' });
res.json({ token });
});

// Protected route
app.get('/protected', (req, res) => {
const token = req.headers['authorization'];
if (!token) return res.status(401).send("Access Denied");

try {
const verified = jwt.verify(token, secretKey);
res.json({ message: "Protected data", user: verified });
} catch (err) {
res.status(400).send("Invalid Token");
}
});

app.listen(3000, () => {
console.log("JWT auth server running on port 3000");
});

44. Passport.js Integration


Install passport and passport-local via npm install passport passport-local.

// File: passportLocal.js
const express = require('express');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const app = express();

app.use(express.json());
app.use(passport.initialize());

passport.use(new LocalStrategy(
function(username, password, done) {
// Replace this with real user validation
if (username === "admin" && password === "password") {
return done(null, { id: 1, username: "admin" });
} else {
return done(null, false, { message: "Incorrect credentials" });
}
}
));

app.post('/login', passport.authenticate('local', { session: false }),


(req, res) => {
res.json({ message: "Logged in successfully", user: req.user });
});

app.listen(3000, () => {
console.log("Passport.js server running on port 3000");
});

45. Handling File Uploads with Multer


Install multer via npm install multer. Ensure an uploads/ folder exists or let Multer
create it.

// File: fileUpload.js
const express = require('express');
const multer = require('multer');
const app = express();

const storage = multer.diskStorage({


destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});
const upload = multer({ storage: storage });

app.post('/upload', upload.single('myFile'), (req, res) => {


res.json({ message: "File uploaded successfully", file: req.file });
});

app.listen(3000, () => {
console.log("File upload server running on port 3000");
});

46. Real-Time Chat with Socket.io


Install socket.io via npm install socket.io express. Save server and client files
separately.
o Server: File: chatServer.js

// File: chatServer.js
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);

io.on('connection', (socket) => {


console.log("New client connected");

socket.on('chat message', (msg) => {


io.emit('chat message', msg);
});

socket.on('disconnect', () => {
console.log("Client disconnected");
});
});

server.listen(3000, () => {
console.log("Socket.io server running on port 3000");
});

o Client: File: chatClient.html

<!DOCTYPE html>
<html>
<head>
<title>Socket.io Chat</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<ul id="messages"></ul>
<form id="chatForm">
<input id="msgInput" autocomplete="off"
/><button>Send</button>
</form>
<script>
const socket = io();
const form = document.getElementById('chatForm');
const input = document.getElementById('msgInput');
const messages = document.getElementById('messages');
form.addEventListener('submit', (e) => {
e.preventDefault();
socket.emit('chat message', input.value);
input.value = '';
});

socket.on('chat message', (msg) => {


const li = document.createElement('li');
li.textContent = msg;
messages.appendChild(li);
});
</script>
</body>
</html>

47. REST API Testing with Postman


This is a Postman collection snippet (save as a JSON file and import into Postman).

{
"info": {
"name": "Test API",
"_postman_id": "12345",
"schema":
"https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "GET Data",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://localhost:3000/api/data",
"protocol": "http",
"host": ["localhost"],
"port": "3000",
"path": ["api", "data"]
}
}
}
]
}

48. Building a Simple Microservice

// File: microservice.js
const express = require('express');
const app = express();
app.use(express.json());

app.get('/microservice', (req, res) => {


res.json({ message: "Response from microservice" });
});
app.listen(3000, () => {
console.log("Microservice running on port 3000");
});

49. Using Environment Variables with dotenv


Install dotenv with npm install dotenv and create a .env file with PORT=3000.

// File: dotenvExample.js
require('dotenv').config();
const express = require('express');
const app = express();

const port = process.env.PORT || 3000;


app.get('/', (req, res) => {
res.send("Environment variable example using dotenv");
});

app.listen(port, () => {
console.log(`Server running on port ${port}`);
});

50. Deployment of a Node.js Application


A simple Express app ready for deployment (e.g., on Heroku or AWS).

// File: deployApp.js
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

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


res.send("Deployed Node.js application running!");
});

app.listen(port, () => {
console.log(`Server running on port ${port}`);
});

You might also like