Showing posts with label Node.js. Show all posts
Showing posts with label Node.js. Show all posts

Friday, 27 December 2024

Clusters of Node.js

Clusters of Node.js

Node.js's cluster module, which allows for the creation of multiple instances of a Node.js application to utilize multiple CPU cores effectively.

Cluster is following round-robin approach.

Workload is equally distribute in our servers and Handling traffic.

Example of Cluster with Node.js

const express = require('express');
const cluster = require('cluster');
const os = require('os');

const PORT = 3300; // Server port
const numCPUs = os.cpus().length; // Total CPU cores available

if (cluster.isPrimary) {
  console.log(`Master process started with PID: ${process.pid}`);

  // Fork workers for each CPU core
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  // Listen for worker exit and optionally restart
  cluster.on('exit', (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} exited. Starting a new worker...`);
    cluster.fork(); // Optionally replace the dead worker
  });
} else {
  const app = express();

  // Middleware to log requests
  app.use((req, res, next) => {
    console.log(`Request handled by process ${process.pid}`);
    next();
  });

  // Example routes
  app.get('/', (req, res) => {
    res.send({
      message: `Handled by process ${process.pid}`,
      route: '/',
    });
  });

  app.get('/about', (req, res) => {
    res.send({
      message: `Handled by process ${process.pid}`,
      route: '/about',
    });
  });

  app.get('/contact', (req, res) => {
    res.send({
      message: `Handled by process ${process.pid}`,
      route: '/contact',
    });
  });

  // Start the server
  app.listen(PORT, () => {
    console.log(`Worker ${process.pid} started. Listening on port ${PORT}`);
  });
}

Thursday, 19 December 2024

Node.js handle uncaught exceptions

Node.js handle uncaught exceptions Node.js handle uncaught exceptions Node.js handle uncaught exceptions

const express = require('express');

const app = express();

// Middleware to parse JSON requests
app.use(express.json());

// A sample route
app.get('/', (req, res) => {
    res.send('Welcome to the Express.js app!');
});

// An example of a route with a potential error
app.get('/error', (req, res) => {
    throw new Error('This is an uncaught exception!');
});

// Global error handling middleware
app.use((err, req, res, next) => {
    console.error('Error caught by middleware:', err.message);
    res.status(500).json({ message: 'Internal Server Error' });
});

// Start the server
const PORT = 3000;
const server = app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

// Handle uncaught exceptions
process.on('uncaughtException', (err) => {
    console.error('Uncaught Exception:', err.message);
    console.error(err.stack);

    // Perform cleanup if necessary, then exit
    server.close(() => {
        console.log('Server closed due to uncaught exception');
        process.exit(1); // Exit with a failure code
    });
});

// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled Rejection at:', promise, 'reason:', reason);

    // Perform cleanup if necessary
    server.close(() => {
        console.log('Server closed due to unhandled rejection');
        process.exit(1); // Exit with a failure code
    });
});

Node.js with Sample Mock API

 Node.js with Sample : Mock API using express

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

// Mock data
const users = [
  { id: 1, name: 'John Doe', email: 'john.doe@example.com' },
  { id: 2, name: 'Jane Smith', email: 'jane.smith@example.com' },
  { id: 3, name: 'Sam Johnson', email: 'sam.johnson@example.com' },
];

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

// Routes
// Get all users
app.get('/api/users', (req, res) => {
  res.status(200).json(users);
});

// Get user by ID
app.get('/api/users/:id', (req, res) => {
  const userId = parseInt(req.params.id, 10);
  const user = users.find(u => u.id === userId);
  if (user) {
    res.status(200).json(user);
  } else {
    res.status(404).json({ message: 'User not found' });
  }
});

// Add a new user
app.post('/api/users', (req, res) => {
  const { name, email } = req.body;
  const newUser = {
    id: users.length + 1,
    name,
    email,
  };
  users.push(newUser);
  res.status(201).json(newUser);
});

// Update a user by ID
app.put('/api/users/:id', (req, res) => {
  const userId = parseInt(req.params.id, 10);
  const userIndex = users.findIndex(u => u.id === userId);
  if (userIndex !== -1) {
    const { name, email } = req.body;
    users[userIndex] = { id: userId, name, email };
    res.status(200).json(users[userIndex]);
  } else {
    res.status(404).json({ message: 'User not found' });
  }
});

// Delete a user by ID
app.delete('/api/users/:id', (req, res) => {
  const userId = parseInt(req.params.id, 10);
  const userIndex = users.findIndex(u => u.id === userId);
  if (userIndex !== -1) {
    users.splice(userIndex, 1);
    res.status(204).send(); // No content
  } else {
    res.status(404).json({ message: 'User not found' });
  }
});

// Start the server
app.listen(PORT, () => {
  console.log(`Mock API is running at http://localhost:${PORT}`);
});

Node.js with create server using Express with middleware function



Express using create server.

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

// Middleware to parse JSON body data
app.use(express.json());

// Custom Middleware to Modify Request Data
app.use((req, res, next) => {
  if (req.body && typeof req.body === 'object') {
    // Add a new property to the request body
    req.body.modified = true;

    // Log the modified request body
    console.log('Modified Request Data:', req.body);
  }
  next(); // Pass control to the next middleware/route handler
});

// Example Route to Test Middleware
app.post('/data', (req, res) => {
  res.send({
    message: 'Request received successfully!',
    requestData: req.body,
  });
});

// Start the Server
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Node : Create server using HTTP

In Node.js, you can create a server using the built-in http module.


const http = require('http');
const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello, World!\n');
});
const port = 3000;
server.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

Tuesday, 17 December 2024

Middleware in Node.js

In Node.js, middleware is a function that acts as an intermediary between software layers to process incoming requests and outgoing responses.

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

const middleFunc = (req, res, next) => {
    req.customText = "Test middleware function...";
    next();
}

app.use(middleFunc);

app.get('/', (req, res) => {
    res.send("Test node app with : "+ req.customText);
});

app.listen(5100);

Events - EventEmitter - Event-Driven Architecture - in Node.js

The event-driven architecture allows asynchronous/synchronous programming, and your application becomes able to perform non-blocking/blocking operations.

EventEmitter class is part of the events module in Node.js.

EventEmitter Methods : .on, .emit (Triggers the event), .once(executes only once), removeListener(Removes Specific Event), .off etc..

Disadvantages : Complex, Difficult to find error, Confusing, etc..


const EventEmitter = require('events');

// Initializing event emitter instances
var eventEmitter = new EventEmitter();

// Declaring listener fun1 to myEvent1
var function1 = (msg) => {
    console.log("Message from function1: " + msg);
};

// Declaring listener fun2 to myEvent2
var function2 = (msg) => {
    console.log("Message from function2: " + msg);
};

// Listening to myEvent with fun1 and fun2
eventEmitter.addListener('myEvent', function1);

// fun2 will be inserted in front of listeners array
eventEmitter.prependListener('myEvent', function2);

// Listing listeners
console.log(eventEmitter.listeners('myEvent'));

// Count the listeners registered to myEvent
console.log(eventEmitter.listenerCount('myEvent'));

// Triggering myEvent
eventEmitter.emit('myEvent', 'Event occurred');