info@webounstraininghub.in
Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside of a web browser. It uses Chrome's V8 JavaScript engine to execute code and is commonly used to build server-side applications.
Node.js handles asynchronous operations using an event-driven, non-blocking I/O model, with callbacks, promises, and 'async/await'
for managing asynchronous tasks.
npm (Node Package Manager) is the default package manager for Node.js. It manages dependencies and allows developers to install, update, and publish packages.
'package.json'
contains metadata about a Node.js project, including its dependencies, scripts, and version. It’s essential for managing project configurations and dependencies.
The Event Loop is the mechanism in Node.js that handles asynchronous callbacks, allowing Node.js to perform non-blocking I/O operations by processing events in a queue.
Promises are a way to handle asynchronous operations in Node.js. They represent a value that may be available now, later, or never, and they allow chaining of asynchronous calls using '.then()'
and '.catch()'
methods.
'require()'
is a CommonJS module syntax used in Node.js, while 'import'
is an ES6 module syntax. 'require()'
is synchronous, while 'import'
is asynchronous.
Node.js uses the 'fs'
module for file I/O operations, which can be performed both synchronously and asynchronously.
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for building web and mobile applications.
Middleware functions in Express.js are functions that have access to the request object ('req'
), the response object ('res
'), and the next middleware function in the application’s request-response cycle.
A RESTful API (Representational State Transfer) is an architectural style for designing networked applications, using HTTP requests to perform CRUD (Create, Read, Update, Delete) operations on resources.
'process.nextTick()'
defers the execution of a function until the next iteration of the Event Loop, while'setImmediate()'
executes a function on the next iteration of the Event Loop after I/O events.
Errors in Node.js can be handled using try-catch blocks, the 'error'
event on EventEmitters, or by passing an error object to the callback function.
EventEmitter is a class in Node.js that facilitates communication between objects. It allows for the creation and handling of custom events using'.on()'
and '.emit()'
methods.
The four types of Streams in Node.js are:
A Buffer is a temporary storage area for binary data. It is used in Node.js to handle raw data, especially when dealing with streams.
The'path'
module provides utilities for working with file and directory paths in Node.js. It helps to resolve, normalize, and join file paths.
The'os'
module provides operating system-related utility methods and properties, such as retrieving information about the system's CPU, memory, and network interfaces.
Environment variables in Node.js are key-value pairs used to configure the application's runtime environment. They allow you to store configuration settings, such as database credentials, API keys, or any other sensitive information, outside of your codebase. This makes the application more secure and flexible, as you can change the environment-specific configurations without modifying the code.
Traditional multi-threaded web servers create a new thread for each request, which can be resource-intensive. Node.js, on the other hand, uses a single-threaded, non-blocking event loop to handle multiple requests concurrently, making it more efficient in handling high-concurrency scenarios.
'readFileSync()'
is a synchronous method that reads a file and blocks the event loop until the operation is complete.'readFile()'
is an asynchronous method that reads a file without blocking the event loop, using a callback to handle the result.
Uncaught exceptions can be handled using'process.on('uncaughtException', callback)',
but it's recommended to handle errors within the application logic itself to avoid unexpected behavior.
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
const fs = require('fs');
const content = 'Some content!';
fs.writeFile('example.txt', content, (err) => {
if (err) {
console.error(err);
return;
}
console.log('File has been written');
});
const http = require('http');
http.get('http://example.com', (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
console.log(data);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
const express = require('express');
const app = express();
app.use(express.static('public'));
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const express = require('express');
const app = express();
app.use(express.json());
app.post('/submit', (req, res) => {
const data = req.body;
res.send(`Received data: ${JSON.stringify(data)}`);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const express = require('express');
const app = express();
const customMiddleware = (req, res, next) => {
console.log('Middleware executed');
next();
};
app.use(customMiddleware);
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Home Page');
});
app.get('/about', (req, res) => {
res.send('About Page');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('Connected to the database');
});
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: String,
age: Number,
email: String
});
const User = mongoose.model('User', userSchema);
const express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const app = express();
app.post('/upload', upload.single('file'), (req, res) => {
res.send(`File uploaded: ${req.file.filename}`);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const express = require('express');
const app = express();
app.get('/', (req, res) => {
throw new Error('Something went wrong');
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const express = require('express');
const session = require('express-session');
const app = express();
app.use(session({
secret: 'secret-key',
resave: false,
saveUninitialized: true,
cookie: { secure: false }
}));
app.get('/', (req, res) => {
if (req.session.views) {
req.session.views++;
res.send(`Views: ${req.session.views}`);
} else {
req.session.views = 1;
res.send('Welcome to the session demo. Refresh the page!');
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});How do you send JSON responses in Express.js?
const express = require('express');
const app = express();
app.use(express.json());
const items = [];
app.get('/items', (req, res) => {
res.json(items);
});
app.post('/items', (req, res) => {
const item = req.body;
items.push(item);
res.status(201).json(item);
});
app.put('/items/:id', (req, res) => {
const { id } = req.params;
const updatedItem = req.body;
items[id] = updatedItem;
res.json(updatedItem);
});
app.delete('/items/:id', (req, res) => {
const { id } = req.params;
items.splice(id, 1);
res.status(204).send();
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
const secretKey = 'your-secret-key';
app.use(express.json());
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (username === 'admin' && password === 'password') {
const token = jwt.sign({ username }, secretKey, { expiresIn: '1h' });
res.json({ token });
} else {
res.status(401).send('Invalid credentials');
}
});
app.get('/protected', (req, res) => {
const token = req.headers['authorization'];
if (token) {
jwt.verify(token, secretKey, (err, decoded) => {
if (err) {
return res.status(401).send('Unauthorized');
}
res.json({ message: 'Protected content', user: decoded.username });
});
} else {
res.status(401).send('No token provided');
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const Koa = require('koa');
const app = new Koa();
app.use(ctx => {
ctx.body = 'Hello World';
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const Koa = require('koa');
const Router = require('koa-router');
const multer = require('@koa/multer');
const app = new Koa();
const router = new Router();
const upload = multer({ dest: 'uploads/' });
router.post('/upload', upload.single('file'), ctx => {
ctx.body = `File uploaded: ${ctx.file.filename}`;
});
app.use(router.routes());
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Home Page');
});
app.use((req, res) => {
res.status(404).send('Page not found');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const net = require('net');
const server = net.createServer((socket) => {
socket.write('Hello, client!');
socket.on('data', (data) => {
console.log('Received: ' + data);
});
socket.on('end', () => {
console.log('Client disconnected');
});
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('Hello, Secure World!\n');
}).listen(3000, () => {
console.log('Server running on port 3000');
});
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 3000 });
server.on('connection', ws => {
ws.on('message', message => {
console.log('Received: ' + message);
});
ws.send('Hello, client!');
});
console.log('WebSocket server running on port 3000');
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
app.use(limiter);
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const interval = setInterval(() => {
console.log('Task running every 2 seconds');
}, 2000);
setTimeout(() => {
clearInterval(interval);
console.log('Task stopped');
}, 10000);
const fetch = require('node-fetch');
const urls = [
'https://jsonplaceholder.typicode.com/posts/1',
'https://jsonplaceholder.typicode.com/posts/2',
'https://jsonplaceholder.typicode.com/posts/3'
];
Promise.all(urls.map(url => fetch(url).then(resp => resp.json())))
.then(results => {
console.log(results);
})
.catch(error => {
console.error('Error:', error);
});
const express = require('express');
const app = express();
const items = Array.from({ length: 100 }).map((_, index) => `Item ${index + 1}`);
app.get('/items', (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const startIndex = (page - 1) * limit;
const endIndex = page * limit;
const results = items.slice(startIndex, endIndex);
res.json({ page, limit, results });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your-email@gmail.com',
pass: 'your-password'
}
});
const mailOptions = {
from: 'your-email@gmail.com',
to: 'recipient-email@gmail.com',
subject: 'Test Email',
text: 'This is a test email.'
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error(error);
} else {
console.log('Email sent: ' + info.response);
}
});
const fs = require('fs');
const readStream = fs.createReadStream('input.txt');
const writeStream = fs.createWriteStream('output.txt');
readStream.pipe(writeStream);
readStream.on('end', () => {
console.log('Data has been copied');
});
const crypto = require('crypto');
const password = 'mysecretpassword';
const hash = crypto.createHash('sha256').update(password).digest('hex');
console.log('Hashed password:', hash);
process.on('SIGINT', () => {
console.log('Received SIGINT. Exiting...');
process.exit();
});
process.on('SIGTERM', () => {
console.log('Received SIGTERM. Exiting...');
process.exit();
});
console.log('Press Ctrl+C to exit');
setInterval(() => {}, 1000); // Keep the process running
We provide expert guidance, personalized support, and resources to help you excel in your digital marketing career.
Timing
9:00 am - 5:00 pm
info@webounstraininghub.in