Skip to content

Instantly share code, notes, and snippets.

@shubham-sharmas
Last active November 17, 2023 18:19
Show Gist options
  • Save shubham-sharmas/827b7651c090f813a21d6aa73bc38106 to your computer and use it in GitHub Desktop.
Save shubham-sharmas/827b7651c090f813a21d6aa73bc38106 to your computer and use it in GitHub Desktop.
This gist demonstrates a CPU-intensive operation using a Node.js Express server with two endpoints: '/non-blocking-operation' and '/complex-blocking-operation'. If we attempt to run the second one then the first one in parallel, the first operation will be blocked until the second one completes. This illustrates that Node.js CPU-intensive operat…
const express = require("express");
const app = express();
// Function to check if a number is prime.
function isPrime(num) {
if (num <= 1) return false;
if (num <= 3) return true;
if (num % 2 === 0 || num % 3 === 0) return false;
for (let i = 5; i * i <= num; i += 6) {
if (num % i === 0 || num % (i + 2) === 0) return false;
}
return true;
}
app.get("/non-blocking-operation", (req, res) => {
res.send(
`<html><body><h1>Timetamp: ${Date.now()}</h1><h2>This request is blocked if /complex-blocking-operation is running!!!</h2></body></html>`,
);
});
app.get("/complex-blocking-operation", (req, res) => {
const startTime = Date.now();
// Simulate a compute-intensive operation by finding prime numbers in a large range.
const maxLimit = 50000000;
const primes = [];
for (let i = 2; i < maxLimit; i++) {
if (isPrime(i)) {
primes.push(i);
}
}
res.send(
`<html><body><h1>Timestamp: ${Date.now()}</h1><h2>Max Limit: ${maxLimit}(Million) => Total primes: ${
primes.length
} <br />Total Execution Time: ${
(Date.now() - startTime) / 1000
} seconds.</h2></body></html>`,
);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment