Nodejs Lab Observation
Nodejs Lab Observation
// File: hello.js
console.log("Hello World");
// 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);
// 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++;
}
// 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));
// File: arrowFunctions.js
const add = (x, y) => x + y;
console.log("Sum:", add(10, 15));
// File: arrays.js
let fruits = ["apple", "banana", "orange"];
fruits.push("mango");
console.log("Fruits:", fruits);
console.log("First fruit:", fruits[0]);
// File: objects.js
const person = {
name: "Alice",
age: 30,
greet: function() { return "Hi, I'm " + this.name; }
};
console.log(person.greet());
// File: jsonExample.js
const obj = { name: "Alice", age: 30 };
const jsonStr = JSON.stringify(obj);
console.log("JSON String:", jsonStr);
// 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();
// 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
// File: iife.js
(function() {
console.log("IIFE executed immediately!");
})();
o File: main.js
// File: main.js
// 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));
// 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();
// 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.");
};
// 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());
// File: recursion.js
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
console.log("Factorial of 5:", factorial(5));
// File: debounce.js
function debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
}
// 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]"));
// File: hello-node.js
console.log("Hello from Node.js");
// 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);
});
// 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.");
});
// 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");
});
// 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");
});
// File: expressIntro.js
const express = require('express');
const app = 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();
app.listen(3000, () => {
console.log("Server running on port 3000");
});
// File: apiGet.js
const express = require('express');
const app = express();
app.listen(3000, () => {
console.log("API server running on port 3000");
});
// File: apiPost.js
const express = require('express');
const app = express();
app.use(express.json());
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());
// 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");
});
// File: expressEJS.js
const express = require('express');
const app = express();
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>
// File: jwtAuth.js
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
app.use(express.json());
const secretKey = "mySecretKey";
// 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");
});
// 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.listen(3000, () => {
console.log("Passport.js server running on port 3000");
});
// File: fileUpload.js
const express = require('express');
const multer = require('multer');
const app = express();
app.listen(3000, () => {
console.log("File upload server running on port 3000");
});
// 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);
socket.on('disconnect', () => {
console.log("Client disconnected");
});
});
server.listen(3000, () => {
console.log("Socket.io server running on port 3000");
});
<!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 = '';
});
{
"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"]
}
}
}
]
}
// File: microservice.js
const express = require('express');
const app = express();
app.use(express.json());
// File: dotenvExample.js
require('dotenv').config();
const express = require('express');
const app = express();
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
// File: deployApp.js
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});