Node.js Real-World Examples

ব্যবহারিক Node.js অ্যাপ্লিকেশন এবং উদাহরণ শিখুন

এক্সপ্রেস সহ RESTful API

সবচেয়ে সাধারণ Node.js অ্যাপ্লিকেশনগুলির মধ্যে একটি হল RESTful API তৈরি করা। এখানে এক্সপ্রেস সহ একটি সহজ কিন্তু ব্যবহারিক টোডো API এর একটি উদাহরণ রয়েছে:

const express = require('express');
const app = express();

// In-memory data store (in a real app, you would use a database)
let todos = [
  { id: 1, title: 'Learn Node.js', completed: false },
  { id: 2, title: 'Build a REST API', completed: false }
];

// Middleware
app.use(express.json());

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

// GET all todos
app.get('/todos', (req, res) => {
  res.json(todos);
});

// GET a single todo
app.get('/todos/:id', (req, res) => {
  const todo = todos.find(t => t.id === parseInt(req.params.id));
  if (!todo) return res.status(404).json({ error: 'Todo not found' });
  res.json(todo);
});

// POST a new todo
app.post('/todos', (req, res) => {
  if (!req.body.title) {
    return res.status(400).json({ error: 'Title is required' });
  }
  
  const newTodo = {
    id: todos.length > 0 ? Math.max(...todos.map(t => t.id)) + 1 : 1,
    title: req.body.title,
    completed: req.body.completed || false
  };
  
  todos.push(newTodo);
  res.status(201).json(newTodo);
});

// PUT (update) a todo
app.put('/todos/:id', (req, res) => {
  const todo = todos.find(t => t.id === parseInt(req.params.id));
  if (!todo) return res.status(404).json({ error: 'Todo not found' });
  
  if (req.body.title) todo.title = req.body.title;
  if (req.body.completed !== undefined) todo.completed = req.body.completed;
  
  res.json(todo);
});

// DELETE a todo
app.delete('/todos/:id', (req, res) => {
  const index = todos.findIndex(t => t.id === parseInt(req.params.id));
  if (index === -1) return res.status(404).json({ error: 'Todo not found' });
  
  const deletedTodo = todos[index];
  todos.splice(index, 1);
  
  res.json(deletedTodo);
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: 'Something went wrong!' });
});

// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

এই উদাহরণটি সঠিক ত্রুটি পরিচালনা এবং স্থিতি কোড সহ একটি সম্পূর্ণ CRUD (তৈরি করুন, পড়ুন, আপডেট করুন, মুছুন) API প্রদর্শন করে৷

প্রমাণীকরণ সিস্টেম

বেশিরভাগ অ্যাপের প্রমাণীকরণ প্রয়োজন। এখানে Node.js-এ JWT-ভিত্তিক প্রমাণীকরণের একটি উদাহরণ রয়েছে:

const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');

const app = express();
app.use(express.json());

// In a real app, use a database
const users = [];

// Secret key for JWT
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';

// Register a new user
app.post('/register', async (req, res) => {
  try {
    const { username, password } = req.body;
    
    // Check if user already exists
    if (users.find(u => u.username === username)) {
      return res.status(400).json({ error: 'Username already exists' });
    }
    
    // Hash the password
    const hashedPassword = await bcrypt.hash(password, 10);
    
    // Create new user
    const user = {
      id: users.length + 1,
      username,
      password: hashedPassword
    };
    
    users.push(user);
    
    res.status(201).json({ message: 'User registered successfully' });
  } catch (error) {
    res.status(500).json({ error: 'Registration failed' });
  }
});

// Login
app.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    
    // Find user
    const user = users.find(u => u.username === username);
    if (!user) {
      return res.status(401).json({ error: 'Invalid credentials' });
    }
    
    // Check password
    const passwordMatch = await bcrypt.compare(password, user.password);
    if (!passwordMatch) {
      return res.status(401).json({ error: 'Invalid credentials' });
    }
    
    // Generate JWT token
    const token = jwt.sign(
      { userId: user.id, username: user.username },
      JWT_SECRET,
      { expiresIn: '1h' }
    );
    
    res.json({ token });
  } catch (error) {
    res.status(500).json({ error: 'Authentication failed' });
  }
});

// Middleware to verify JWT token
function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];
  
  if (!token) return res.status(401).json({ error: 'Authentication required' });
  
  jwt.verify(token, JWT_SECRET, (err, user) => {
    if (err) return res.status(403).json({ error: 'Invalid or expired token' });
    req.user = user;
    next();
  });
}

// Protected route example
app.get('/profile', authenticateToken, (req, res) => {
  res.json({ user: req.user });
});

app.listen(8080, () => {
  console.log('Authentication server running on port 8080');
});

ফাইল আপলোড পরিষেবা

Node.js , :

const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

const app = express();
app.use(express.json());
app.use(express.static('public'));

// Configure multer storage
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = './uploads';
    
    // Create directory if it doesn't exist
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir);
    }
    
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    // Generate unique filename with original extension
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, file.fieldname + '-' + uniqueSuffix + ext);
  }
});

// File filter function
const fileFilter = (req, file, cb) => {
  // Accept images and PDFs only
  if (file.mimetype.startsWith('image/') || file.mimetype === 'application/pdf') {
    cb(null, true);
  } else {
    cb(new Error('Unsupported file type'), false);
  }
};

const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: { fileSize: 5 * 1024 * 1024 } // 5MB limit
});

// Serve upload form
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// Single file upload endpoint
app.post('/upload/single', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ error: 'No file uploaded' });
  }
  
  res.json({
    message: 'File uploaded successfully',
    file: {
      filename: req.file.filename,
      originalname: req.file.originalname,
      mimetype: req.file.mimetype,
      size: req.file.size
    }
  });
});

// Multiple file upload endpoint (max 5)
app.post('/upload/multiple', upload.array('files', 5), (req, res) => {
  if (!req.files || req.files.length === 0) {
    return res.status(400).json({ error: 'No files uploaded' });
  }
  
  res.json({
    message: `${req.files.length} files uploaded successfully`,
    files: req.files.map(file => ({
      filename: file.filename,
      originalname: file.originalname,
      mimetype: file.mimetype,
      size: file.size
    }))
  });
});

// Error handling middleware
app.use((err, req, res, next) => {
  if (err instanceof multer.MulterError) {
    // Multer-specific errors
    return res.status(400).json({ error: err.message });
  } else if (err) {
    // Other errors
    return res.status(500).json({ error: err.message });
  }
  next();
});

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

মাইক্রোসার্ভিস আর্কিটেকচার

Node.js . :

// src/index.js
const express = require('express');
const routes = require('./routes');
const errorHandler = require('./middleware/errorHandler');
const logger = require('./middleware/logger');
const config = require('./config');

const app = express();

// Middleware
app.use(express.json());
app.use(logger);

// Health check
app.get('/health', (req, res) => {
  res.status(200).json({ status: 'ok', service: 'product-catalog', timestamp: new Date() });
});

// Routes
app.use('/api/products', routes.productRoutes);

// Error handling
app.use(errorHandler);

// Start server
app.listen(config.PORT, () => {
  console.log(`Product catalog service running on port ${config.PORT}`);
});

// Handle graceful shutdown
process.on('SIGTERM', () => {
  console.log('SIGTERM received, shutting down gracefully');
  // Close database connections, etc.
  process.exit(0);
});
// src/routes/productRoutes.js
const express = require('express');
const productController = require('../controllers/productController');

const router = express.Router();

router.get('/', productController.getAllProducts);
router.get('/:id', productController.getProductById);
router.post('/', productController.createProduct);
router.put('/:id', productController.updateProduct);
router.delete('/:id', productController.deleteProduct);

module.exports = router;

🏗️সর্বোত্তম অনুশীলন:

একটি সত্যিকারের মাইক্রোসার্ভিসেস আর্কিটেকচারে, প্রতিটি পরিষেবার নিজস্ব সংগ্রহস্থল, বিতরণ পাইপলাইন এবং ডাটাবেস থাকে।

টাস্ক পরিকল্পনা

Node.js :

const cron = require('node-cron');
const nodemailer = require('nodemailer');
const express = require('express');

const app = express();

// Configure mail transporter (this is just an example)
const transporter = nodemailer.createTransport({
  host: 'smtp.example.com',
  port: 587,
  secure: false,
  auth: {
    user: 'user@example.com',
    pass: 'password'
  }
});

// Schedule a task to run every day at 9:00 AM
cron.schedule('0 9 * * *', async () => {
  console.log('Running daily report task');
  
  try {
    // Generate report data (in a real app, fetch from database)
    const reportData = {
      date: new Date().toISOString().split('T')[0],
      metrics: {
        users: 1250,
        orders: 350,
        revenue: 12500
      }
    };
    
    // Send email with report
    await transporter.sendMail({
      from: 'system@example.com',
      to: 'admin@example.com',
      subject: `Daily Report - ${reportData.date}`,
      html: `
        

Daily Report

Date: ${reportData.date}

Key Metrics

  • Users: ${reportData.metrics.users}
  • Orders: ${reportData.metrics.orders}
  • Revenue: $${reportData.metrics.revenue}
` }); console.log('Daily report email sent successfully'); } catch (error) { console.error('Error sending daily report:', error); } }); // Schedule database backup every Sunday at midnight cron.schedule('0 0 * * 0', () => { console.log('Running weekly database backup'); // In a real app, you would run a database backup command here }); // Clean up temporary files every hour cron.schedule('0 * * * *', () => { console.log('Cleaning up temporary files'); // In a real app, you would delete old temporary files here }); // API to add a one-time job const scheduledJobs = new Map(); app.use(express.json()); app.post('/schedule-job', (req, res) => { const { id, scheduledTime, task } = req.body; if (!id || !scheduledTime || !task) { return res.status(400).json({ error: 'Missing required parameters' }); } const jobTime = new Date(scheduledTime).getTime(); const currentTime = Date.now(); if (jobTime <= currentTime) { return res.status(400).json({ error: 'Scheduled time must be in the future' }); } // Schedule the job const timeout = setTimeout(() => { console.log(`Executing job: ${id}`); // In a real app, use a job queue like Bull to handle the tasks console.log(`Task: ${task}`); scheduledJobs.delete(id); }, jobTime - currentTime); scheduledJobs.set(id, { timeout, scheduledTime, task }); res.status(201).json({ message: 'Job scheduled successfully', job: { id, scheduledTime, task } }); }); // Start server app.listen(8080, () => { console.log('Task scheduler running on port 8080'); });

রিয়েল-টাইম অ্যানালিটিক্স ড্যাশবোর্ড

WebSockets এবং Chart.js এর সাথে রিয়েল-টাইমে ব্যবহারের মেট্রিকগুলি নিরীক্ষণ এবং কল্পনা করুন:

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const { v4: uuidv4 } = require('uuid');

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: '*', // In production, replace with your frontend domain
    methods: ['GET', 'POST']
  }
});

// In-memory store for analytics data (use a database in production)
const analyticsData = {
  pageViews: {},
  activeUsers: new Set(),
  events: []
};

// Track page views
app.use((req, res, next) => {
  const page = req.path;
  analyticsData.pageViews[page] = (analyticsData.pageViews[page] || 0) + 1;
  
  // Emit update to all connected clients
  io.emit('analytics:update', {
    type: 'pageView',
    data: { page, count: analyticsData.pageViews[page] }
  });
  
  next();
});

// Track custom events
app.post('/track', express.json(), (req, res) => {
  const { event, data } = req.body;
  const eventId = uuidv4();
  const timestamp = new Date().toISOString();
  
  const eventData = { id: eventId, event, data, timestamp };
  analyticsData.events.push(eventData);
  
  // Keep only the last 1000 events
  if (analyticsData.events.length > 1000) {
    analyticsData.events.shift();
  }
  
  // Emit event to all connected clients
  io.emit('analytics:event', eventData);
  
  res.status(201).json({ success: true, eventId });
});

// WebSocket connection handling
io.on('connection', (socket) => {
  const userId = socket.handshake.query.userId || 'anonymous';
  analyticsData.activeUsers.add(userId);
  
  // Send initial data to the newly connected client
  socket.emit('analytics:init', {
    pageViews: analyticsData.pageViews,
    activeUsers: analyticsData.activeUsers.size,
    recentEvents: analyticsData.events.slice(-50)
  });
  
  // Update all clients about the new active user count
  io.emit('analytics:update', {
    type: 'activeUsers',
    data: analyticsData.activeUsers.size
  });
  
  // Handle disconnection
  socket.on('disconnect', () => {
    analyticsData.activeUsers.delete(userId);
    io.emit('analytics:update', {
      type: 'activeUsers',
      data: analyticsData.activeUsers.size
    });
  });
  
  // Handle custom events from the client
  socket.on('analytics:event', (data) => {
    const eventId = uuidv4();
    const timestamp = new Date().toISOString();
    const eventData = { id: eventId, ...data, timestamp, userId };
    
    analyticsData.events.push(eventData);
    if (analyticsData.events.length > 1000) {
      analyticsData.events.shift();
    }
    
    io.emit('analytics:event', eventData);
  });
});

// API to get analytics data
app.get('/api/analytics', (req, res) => {
  res.json({
    pageViews: analyticsData.pageViews,
    activeUsers: analyticsData.activeUsers.size,
    totalEvents: analyticsData.events.length,
    recentEvents: analyticsData.events.slice(-50)
  });
});

// Serve the dashboard
app.use(express.static('public'));

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`Analytics server running on port ${PORT}`);
  console.log(`Dashboard available at http://localhost:${PORT}/dashboard.html`);
});

⚠️উত্পাদন ব্যবহারের জন্য নোট:

একটি ডাটাবেসে বিশ্লেষণী ডেটা বজায় রাখা এবং যথাযথ প্রমাণীকরণ বাস্তবায়নের কথা বিবেচনা করুন।

ব্যবহারিক Node.js অ্যাপ্লিকেশনের জন্য সর্বোত্তম অনুশীলন

উত্পাদন Node.js অ্যাপ্লিকেশন তৈরি করার সময়, এই সর্বোত্তম অনুশীলনগুলি অনুসরণ করুন:

অ্যাপ্লিকেশন ফ্রেমওয়ার্ক

একটি পরিষ্কার প্রকল্প কাঠামো ব্যবহার করুন(MVC বা অনুরূপ)
রুট থেকে পৃথক ব্যবসা যুক্তি
পরিবেশ ভেরিয়েবলে কনফিগারেশন রাখুন
যেখানে প্রয়োজন সেখানে নির্ভরশীল ইন্ডেন্টেশন ব্যবহার করুন

ত্রুটি হ্যান্ডলিং

বিশ্বব্যাপী ত্রুটি হ্যান্ডলিং মিডলওয়্যার প্রয়োগ করুন
সঠিক প্রসঙ্গ সহ ত্রুটিগুলি লগ করুন৷
উপযুক্ত HTTP স্ট্যাটাস কোড প্রদান করুন
ধরা না পড়া ব্যতিক্রম এবং অনির্বাচিত প্রতিশ্রুতিগুলি পরিচালনা করুন

নিরাপত্তা

সর্বদা ব্যবহারকারীর ইনপুট যাচাই এবং পরিমার্জন করুন
HTTPS এবং নিরাপদ কুকি ব্যবহার করুন
API-এর জন্য হার সীমিত করা
নির্ভরতা আপডেট রাখুন
নিরাপত্তা শিরোনাম ব্যবহার করুন (Helmet.js)

কর্মক্ষমতা এবং পরিমাপযোগ্যতা

HTTP প্রতিক্রিয়ার জন্য কম্প্রেশন ব্যবহার করুন
সঠিক ক্যাশিং কৌশল প্রয়োগ করুন
মাল্টি-কোর অ্যাপ্লিকেশনের জন্য ক্লাস্টার বা PM2 ব্যবহার করুন
মেমরি ব্যবহার নিরীক্ষণ এবং আবর্জনা সংগ্রহ সক্রিয়
ভাল পঠনযোগ্যতার জন্য async/await ব্যবহার করুন

💡পেশাগত পরামর্শ:

প্রোডাকশন অ্যাপ্লিকেশনগুলির জন্য, সমস্যাগুলি দ্রুত সনাক্ত করতে এবং সমাধান করতে সর্বদা বিশদ পর্যবেক্ষণ, লগিং এবং সতর্কতা অন্তর্ভুক্ত করুন।

অনুশীলন করুন

Node.js , .

Cookies
✗ ভুল! কুকিগুলি প্রমাণীকরণের জন্য ব্যবহার করা যেতে পারে, তবে JWTগুলি সাধারণত নিরাপদে পক্ষগুলির মধ্যে অনুরোধগুলি বিনিময় করতে ব্যবহৃত হয়
Sessions
✗ ভুল! সেশনগুলি প্রমাণীকরণের জন্য ব্যবহার করা যেতে পারে, তবে JWTগুলি সাধারণত পক্ষগুলির মধ্যে নিরাপদে অনুরোধগুলি বিনিময় করতে ব্যবহৃত হয়
JWT
✓ ঠিক আছে! JWTs (JSON ওয়েব টোকেন) হল একটি উন্মুক্ত মান যা সাধারণত পক্ষগুলির মধ্যে নিরাপদে অনুরোধ বিনিময় করতে ব্যবহৃত হয়
OAuth
✗ ভুল! OAuth হল একটি প্রমাণীকরণ প্রোটোকল, তবে JWT গুলি সাধারণত পক্ষগুলির মধ্যে অনুরোধ বিনিময় করার জন্য টোকেন ব্যবহার করা হয়