DEV Community

M DISHA SHETTY
M DISHA SHETTY

Posted on • Edited on

1

Utilizing Worker Threads in Node.js to Efficiently Facilitate the Upload Process of a File into an Amazon S3 Bucket.

Image description
LINK FOR FLOWCHART

*How to Implement *

File Upload Process:

The user will upload the file via /upload endpoint and API immediately returns a response: "File uploaded successfully
The file details (path, job_applicant_id) are added to a queue for processing.
A worker thread picks up the file and uploads it to S3 Bucket.
THe Path is stored in Database as well with the path name

Fetching the File:

1.When a user requests the file via and API(fetch/job_applicant_id/filepath) by the path name

2.The API generates a signed URL for temporary access and returns it

IMPLEMENTATION PART:

1. File Upload API
Uses multer to handle file uploads.
Adds the file path to a queue for processing.
Responds immediately without waiting for the file to upload.

const express = require('express');
const multer = require('multer');
const threadController = require('./threadController');

const app = express();
const upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('file'), (req, res) => {
    const { job_applicant_id } = req.body;
    const filePath = req.file.path;
    const fileName = req.file.originalname;

    threadController.addToQueue(job_applicant_id, filePath, fileName);
    res.json({ message: 'File uploaded successfully' });
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});
Enter fullscreen mode Exit fullscreen mode

2. Worker Thread for Uploading to S3
Picks up files from the queue.
Uploads them to S3 under job_applicant_id.

const { isMainThread, parentPort, workerData } = require('worker_threads');
const AWS = require('aws-sdk');
const fs = require('fs');

AWS.config.update({
    accessKeyId: 'AWS_ACCESS_KEY',
    secretAccessKey: 'AWS_SECRET_KEY',
    region: 'us-east-1'
});

const s3 = new AWS.S3();

if (!isMainThread) {
    const { job_applicant_id, filePath, fileName } = workerData;
    const fileStream = fs.createReadStream(filePath);

    const params = {
        Bucket: 'my-file-bucket',
        Key: `${job_applicant_id}/${fileName}`,
        Body: fileStream,
        ContentType: 'application/pdf'
    };

    s3.upload(params).promise()
        .then(data => console.log(`File uploaded: ${data.Location}`))
        .catch(err => console.error(`Upload failed: ${err.message}`));
}

Enter fullscreen mode Exit fullscreen mode

3. Fetch File API
Retrieves a temporary signed URL to access the file.
app.get('/get-file/:job_applicant_id/:file_name', (req, res) => {

` const { job_applicant_id, file_name } = req.params;

    const params = {
        Bucket: 'my-file-bucket',
        Key: `${job_applicant_id}/${file_name}`,
        Expires: 60 * 5 // Link valid for 5 minutes
    };

    const url = s3.getSignedUrl('getObject', params);
    res.json({ url });
});`

Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • 0:56 --last-failed
  • 2:34 --only-changed
  • 4:27 --repeat-each
  • 5:15 --forbid-only
  • 5:51 --ui --headed --workers 1

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Click on any timestamp above to jump directly to that section in the tutorial!

Watch Full Video 📹️

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay