Categories
JavaScript Answers

How to get response from S3 getObject in Node.js?

Spread the love

Sometimes, we want to get response from S3 getObject in Node.js.

In this article, we’ll look at how to get response from S3 getObject in Node.js.

How to get response from S3 getObject in Node.js?

To get response from S3 getObject in Node.js, we can get the file chunks with the GetObjectCommand constructor.

For instance, we write

const { GetObjectCommand, S3Client } = require("@aws-sdk/client-s3");
const client = new S3Client();

const getObject = (Bucket, Key) => {
  return new Promise(async (resolve, reject) => {
    const getObjectCommand = new GetObjectCommand({ Bucket, Key });
    try {
      const response = await client.send(getObjectCommand);
      let responseDataChunks = [];
      response.Body.once("error", (err) => reject(err));
      response.Body.on("data", (chunk) => responseDataChunks.push(chunk));
      response.Body.once("end", () => resolve(responseDataChunks.join("")));
    } catch (err) {
      return reject(err);
    }
  });
};

to create a GetObjectCommand object with an object with the Bucket and Key of the file to get.

Then we call client.send with getObjectCommand to send the command to get the file.

Then we call response.Body.on with 'data' to get the data chunks with the callback.

And then we call response.Body.once with 'end' to join the chunks together and call resolve with the joined chunks to use that as the value of the returned promise.

Conclusion

To get response from S3 getObject in Node.js, we can get the file chunks with the GetObjectCommand constructor.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *