Converting ExpressJS Function for Multipart Uploading to AWS Lambda

Looking for advice on converting this Express.js function to AWS Lambda for Node.js 18.

const upload = multer()

// Write received chunk to S3 bucket
app.post('/upload', upload.single("file"), (req, res) => {
  const { index, fileName } = req.body;
  const file = req.file;

  const s3Params = {
    Bucket: bucketName,
    Key: fileName,
    Body: file.buffer,
    PartNumber: Number(index) + 1,
    UploadId: req.query.uploadId
  };

  s3.uploadPart(s3Params, (err, data) => {
    if (err) {
      console.log(err);
      return res.status(500).json({ success: false, message: 'Error uploading chunk' });
    }

    return res.json({ success: true, message: 'Chunk uploaded successfully' });
  });
});

To start a Lambda function, use the following syntax:

exports.handler = async (event) => { }

Answer №1

To simplify the process, consider using a base64 string instead of multipart when working with AWS Lambda.

However, if you prefer to use multipart, it is possible to create an Express.js app within a Lambda function. Below is an example:

const upload = multer()

// Receive chunk and write it to S3 bucket
app.post('/upload', upload.single("file"), (req, res) => {
  const { index, fileName } = req.body;
  const file = req.file;
 
  const s3Params = {
    Bucket: bucketName,
    Key: fileName,
    Body: file.buffer,
    PartNumber: Number(index) + 1,
    UploadId: req.query.uploadId
  };

  s3.uploadPart(s3Params, (err, data) => {
    if (err) {
      console.log(err);
      return res.status(500).json({ success: false, message: 'Error uploading chunk' });
    }

    return res.json({ success: true, message: 'Chunk uploaded successfully' });
  });
});

Implement this in your lambda function by adding the following code:

const awsServerlessExpress = require('aws-serverless-express');
const app = require('./app.js');
const server = awsServerlessExpress.createServer(app)

module.exports.handler = (event, context) => awsServerlessExpress.proxy(server, event, context);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js: Capturing requests and responses for console logging

I'm currently working on a Hapi server using Good to log all requests and responses to the console. I've been able to successfully log responses but I'm facing issues with logging the body of the response, and for requests, I'm not gett ...

When using Angular $HTTP, CORS is supported when working with application/x-www-form-urlencoded, but there is a problem with OPTIONS 404

I have successfully implemented a Node + ExpressJS with CORS setup using this middleware. However, I am facing issues when working with POST requests. Here is what works: $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded"; ...

Issue with Nodemailer: My frontend site is unable to send emails using Node Mailer when triggered from a separate IP address

Within my frontend portfolio, there exists an option to send emails which triggers a post request to nodemailer located in the backend. As of now, my portfolio has been successfully deployed on firebase and the backend is being hosted on the localhost serv ...

Failure to reach asynchronous callback, causing response to stall

I've encountered an issue and I'm unsure of the necessary steps to resolve it. The data retrieval process is working correctly, but the responseCallback isn't triggering, preventing me from reaching the res.json call with the response array. ...

"There is an issue with the payload size: request entity is too large. What is the solution for handling this in Nest

I am facing an issue where I need to send a request containing a large base64 string, approximately around 2 MB. However, the server keeps throwing an error message. How can I prevent this error from occurring: [Nest] 1666 - 11/01/2021, 1:50:58 PM ERRO ...

Exploring the Possibilities of Socket.io Integration with Express 4 Across Multiple Pages: Dive Into Socket.io Sample Code

Just to clarify, I came across a similar question on Stack Overflow before posting this. However, the answer there was not clear to me and my query is slightly different. Thus, I am hoping for a more straightforward explanation. The Express Generator sets ...

"Distributing SQL Server Express along with my software: A step-by-step guide

I have created a software application that utilizes SQL Server Express. For legal clarification, I am seeking confirmation regarding the legality of my software. Users have the option to click on a button within my program that initiates the installation ...

Converting basic text into JSON using Node.js

Today I am trying to convert a text into JSON data. For example: 1 kokoa#0368's Discord Profile Avatar kokoa#0000 826 2 Azzky 陈东晓#7475's Discord Profile Avatar Azzky 陈东晓#0000 703 3 StarKleey 帅哥#6163's Di ...

The process of including additional parameters in each request in node.js

My goal is to incorporate an optional referral parameter into every URL of my node.js application. Currently, I have a working solution but I am exploring more efficient and elegant methods to achieve the same without unnecessarily complicating my code: a ...

Is it possible to reduce dependencies on Symfony and Assetic? How can I adjust permissions for node_modules to avoid using sudo?

Currently, I am facing an issue while trying to properly install and run Less with Symfony and Assetic on Ubuntu 12.04 LTS due to a permissions problem. My main question is how can I adjust the permissions so that running app/console assetic:dump does not ...

Encountering an issue when attempting to establish a connection to Redis using a cache manager within a Nest

Incorporating the NestJS framework into my project and utilizing Cash Manager to connect with Redis cache. Successfully connected with Redis, however encountering an error when attempting to use methods like set/get which shows 'set is not a function& ...

Struggling with Node.js server debugging? My breakpoints keep getting skipped by the debugger in VSCode - how can I fix this?

Currently, I'm in the process of debugging a Next.js application with a custom server. In normal situations, I would run this server with a Yarn script labeled dev, which basically executes node server.js. To assist me in this endeavor, I decided to ...

Execute a node.js package on a web server indefinitely

Currently, I am using a blog platform called specter, which launches once I execute the command npm start. The site is only accessible through the URL after running npm start. Whenever I stop the package by using command-c in the terminal, the site goes ...

Fuzzy images and distorted pdf files generated using puppeteer

Having trouble with rendering clear images using Puppeteer for PDF, WebP, and PNG exports. Even when following a simple example from the official documentation: const browser = await puppeteer.launch(); const page = await browser.newPage(); // Navigate t ...

Oh no! A critical mistake has occurred: Mark-compact operations are not working efficiently near the heap limit, leading to a failed allocation due to the

My project is not particularly complex, I only just started it. However, when I run the command npm run dev, node js consumes more than 4GB of memory and eventually crashes with a fatal error: --- Last few GCs --- [16804:0000018EB02350F0] 128835 ms: Mar ...

I am attempting to retrieve the initial three results from my MySQL database using Node.js, but I keep encountering an error

Below is the code I am currently using: con.query('SELECT * FROM tables', function(err, results) { if (err) throw err console.log(results[0].rawname) for(var i= 0; i <= 3; i++) { ...

Challenges with updating npm iteration

Trying to update npm version resulted in: npm -v 5.6.0 sudo npm install -g npm@6 /home/${user}/.npm-global/bin/npm -> /home/${user}/.npm-global/lib/node_modules/npm/bin/npm-cli.js /home/${user}/.npm-global/bin/npx -> /home/${user}/.npm-global/lib/no ...

Winston prefers JSON over nicely formatted strings for its output

I have implemented a basic Winston logger within my application using the following code snippet: function Logger(success, msg) { let now = new Date().toUTCString(); let logger = new (winston.Logger)({ transports: [ new (winsto ...

Exploring the Implementation of Middleware in node.js with MVC Routing

Encountering an issue when adding a middleware to the routes of my application. The structure is detailed in the images linked below. Middleware Config: https://i.stack.imgur.com/0iCKI.png Controller Setup: https://i.stack.imgur.com/XyvPw.png Routes C ...

How can we compare mongoose Dates without considering the time and group by multiple properties at the same

Although this question may seem similar to others, we apologize for any confusion as our business case differs from existing questions. In our project, we are utilizing Nodejs and MongoDB to develop the REST API. We have a collection named : EMPLog conta ...