Search code examples
typescriptamazon-web-servicesamazon-s3aws-sdk-jsaws-sdk-nodejs

AWS Javascript/Typescript SDK download s3 file


I would like to use the AWS Javascript SDK to download a file from s3.

My current code is

import {
    S3Client,
    GetObjectCommand,
} from "@aws-sdk/client-s3";

const s3 = new S3Client({region: REGION});


const downloadParams = {Bucket: bucketName, Key: keyName};

const downloadFile = async () => {
    try {
        const data = await s3.send(new GetObjectCommand(downloadParams));
        // fs.writeFileSync("output.txt", data.Body);
        // fs.writeFile("output.txt", data.Body);
        console.log("Success, bucket returned", data);
    } catch (err) {
        console.log("Error", err);
    }
}
downloadFile();

But I am not sure how to get the file data from the return data.

Data.body does not get the file data.


Solution

  • Please refer to this JS example in the AWS Github repo. It shows you how to get the object from the Amazon S3 bucket. It is returned as a ReadableStream.

    https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascriptv3/example_code/s3/src/s3_getobject.js

    Updated URL:

    https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/s3/actions/get-object.js