Check and Download Files from AWS S3

JS
S
JavaScript

Simple example of Using AWS SDK to check if a PDF exists before downloading. In this scenario there are 2 names for the same type of object (one regular, the other one with underscore).

1import AWS from 'aws-sdk';
2const s3 = new AWS.S3();
3
4const key1 = `${id}.pdf`;
5const params1 = {
6    Key: key1,
7    Bucket: bucket
8};
9const key2 = `_${id}.pdf`;
10const params2 = {
11    Key: key2,
12    Bucket: bucket
13};
14
15res.writeHead(200, {
16    'Content-Type': 'application/pdf',
17    'Content-Disposition': `${id}.pdf`
18});
19
20// Check if key exists on bucket before reading
21s3
22    .getObject(params1)
23    .promise()
24    .then(() => {
25        // Download via params1
26        s3
27            .getObject(params1)
28            .createReadStream()
29            .pipe(res);
30    })
31    .catch(error => {
32        // Download via params2
33        s3
34            .getObject(params2)
35            .createReadStream()
36            .pipe(res);
37    });

Created on 3/29/2018