Skip to content

Instantly share code, notes, and snippets.

@pbaio
Last active March 7, 2017 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pbaio/3ead320ab84f3e14bc4d0323aacf15fa to your computer and use it in GitHub Desktop.
Save pbaio/3ead320ab84f3e14bc4d0323aacf15fa to your computer and use it in GitHub Desktop.
Downloads a File from a Bucket, saves it to a location on disk and returns a Promise
'use strict';
const fs = require('fs');
const AWS = require('aws-sdk');
const S3 = new AWS.S3(); // pass in config if you need to, use default credentials location
module.exports = (bucket, key, dest) => {
return new Promise((resolve, reject) => {
let ws = fs.createWriteStream(dest);
ws.once('error', (err) => {
return reject(err);
});
ws.once('finish', () => {
console.log(`File Downloaded! ${dest}`);
return resolve(dest);
});
let s3Stream = S3.getObject({
Bucket: bucket,
Key: key
}).createReadStream();
// Under load this will prevent first few bytes from being lost
s3Stream.pause()
s3Stream.on('error', (err) => {
return reject(err);
});
s3Stream.pipe(ws);
s3Stream.resume();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment