Last active
March 7, 2017 20:41
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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