This project demonstrates how to offload CPU-intensive tasks (like image resizing and video compression) using the worker_threads module in Node.js. By delegating heavy processing to worker threads, the main thread remains free to handle incoming HTTP requests, making the application highly scalable and responsive.
- 📸 Image Resizing (uses
sharpin a worker thread) - 🎥 Video Compression (uses
ffmpegviafluent-ffmpegin a worker thread) - ⚡ Efficient processing without blocking the main thread
- 🧵 Utilizes Node.js
worker_threadsfor parallelism - 📁 File upload via
multer - 🗃️ Output files are saved to separate folders (
resized/,processed/)
image-video-processor/
├── controllers/
│ ├── imageController.js
│ └── videoController.js
├── routes/
│ ├── image.js
│ └── video.js
├── workers/
│ ├── resizeWorker.js
│ └── videoWorker.js
├── resized/ # Processed images
├── processed/ # Compressed videos
├── uploads/ # Temporary uploads
├── server.js
├── package.json
└── README.md
Install the required packages:
npm install express multer sharp fluent-ffmpegYou also need FFmpeg installed on your system:
# Arch
sudo pacman -S ffmpeg
# Ubuntu/Debian
sudo apt install ffmpeg
# macOS
brew install ffmpegIn traditional Node.js (single-threaded), CPU-intensive tasks block the event loop, making the app unresponsive. With worker_threads, heavy jobs run in parallel threads, leaving the main thread free to handle more requests.
Endpoint:
POST /api/image/resizePayload:
- Type:
multipart/form-data - Field:
image(file)
curl Example:
curl -X POST http://localhost:5000/api/image/resize \
-H "Content-Type: multipart/form-data" \
-F "image=@/absolute/path/to/image.jpg"Response:
{
"message": "Image resized successfully",
"output": "resized/resized-image-1696600000000.jpg"
}Endpoint:
POST /api/video/compressPayload:
- Type:
multipart/form-data - Field:
video(file)
curl Example:
curl -X POST http://localhost:5000/api/video/compress \
-H "Content-Type: multipart/form-data" \
-F "video=@/absolute/path/to/video.mp4"Response:
{
"message": "Video processed successfully",
"output": "processed/compressed-video-1696600000000.mp4"
}# Start server
node server.jsServer runs on:
http://localhost:5000- Node.js
- Express.js
- worker_threads
- multer
- sharp
- fluent-ffmpeg