How to Download a File from AWS S3 in JavaScript (Node JS Environment)

AWS S3 is a file storage service that allows you to store files in buckets. It also provides SDK to interact with the service programmatically.

This tutorial teaches you the different methods to download a file from AWS S3 in JavaScript (Node JS Environment). It explains how to download the file server side and generate a signed URL that can be used to download files from the Client side.

Specifying Security Credentials

The tutorial assumes the AWS security credentials are configured already on your computer.

If NOT configured, you can specify the credentials in your program using the following code. However, using the security credentials on your program explicitly is not recommended.

AWS.config.update(
  {
    accessKeyId: “<your key>”,
    secretAccessKey: “<your secret key>”,
  }
);

Download a File from AWS S3 Using JavaScript (Server Side)

The getObject() method retrieves an object from the S3 service.

Use this method when you want to download a file from the AWS S3 in the server-side application.

  • Import the file system library and the aws-sdk using require
  • Create a new S3 client using the new aws.S3
  • Create a parameters with the bucket name and the key of the object
  • Invoke the getObject() method in the S3 client. It will retrieve the file from the S3 service and return a response
  • Write the file to the disk using the fs.writeFileSync() method and pass the file name and the getObject method’s response as a parameter
  • The file will be downloaded and saved with the specified file name

Code

const fs = require('fs');

const aws = require('aws-sdk');
const s3 = new aws.S3({ apiVersion: '2006-03-01' });

var getParams = {
  Bucket: 'bucket_name',
  Key: 'filename.txt'
}

s3.getObject(getParams, function (err, data) {
  if (err) {
    return err;
  }

fs.writeFileSync('downloadedFile.txt', data.Body);
});

Download a File from AWS S3 Using Signed URL (For Client Side)

When downloading a file from AWS S3 on the client side, you must use the pre-signed URLS because the client side doesn’t have the AWS security credentials configured. Without the security credentials, it is not possible to download private objects from the S3 service.

Hence, you must create a pre-signed URL from your server-side application and return it to the client. The client-side browser/application can download the file object from the pre-signed URL.

The getSignedURL() method creates a pre-signed URL from the given operation.

Use this method when you want enable users to download the files from S3 and do not want to share the security credentials

  • Create a new S3 client with the apiVersion, signatureVersion and the region properties
  • Initialize the bucket name and the object key
  • Define the expiration seconds for the Signed URL. The signed URL will expire after this defined time
  • Create a Signed URL using the getSignedURL() method for the getObject operation and pass the bucket name, object name and the expiration seconds
  • Upon successful execution, a signed URL will be created that will be valid for the defined time.
  • You can pass on the URL to the client application, and the client can download the file using it without knowing any security credentials

Code

const aws = require('aws-sdk');

const s3 = new aws.S3({ apiVersion: '2006-03-01' , signatureVersion: 'v4',  region: 'ap-south-1'});

const bucketName = 'bucketname'

const objectKey = 'filename.txt'

const signedUrlExpireSeconds = 60 * 5;

const url = s3.getSignedUrl('getObject', {
 Bucket: bucketName,
 Key: objectKey,
 Expires: signedUrlExpireSeconds
})

console.log(
  url
);

Output

https://bucketname.s3.ap-south-1.amazonaws.com/filename.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAsdfgsfgsdfgsdfFPFLXVJ%2F20230405%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20230405T111425Z&X-Amz-Expires=300&X-Amz-Signature=3e11164464564456576815291b8e36d0675370c6caabb00761976afb55&X-Amz-SignedHeaders=host

Using the PRE-Signed URL

Use the following JavaScript code to download a file from the pre-signed URL generated in the previous section. It will download the file from the URL and save it in the filename specified.

const link = document.createElement('a');
link.href = “Place the presigned url here“;
link.download = "test.txt";
link.click();

Alternatively, you can open the pre-signed URL in a new window. It will automatically identify the file type and show dialogue to save it.

The file name available in the S3 object will be used as a default file name.

window.open( presignedUrl, '_blank' );

After creating this program, we tried to commit the program to Git from VSCode. But we faced an error Encountered old-style “xxx” that should be “%(prefix)/xxx”. We solved the error using the tutorial: Solved – VSCode Git Error – Encountered old-style “xxx” that should be “%(prefix)/xxx”. If you have the Git Error, you can check this tutorial too.

If you have any questions, feel free to comment below.

Leave a Comment