Created
August 11, 2017 16:27
-
-
Save milesrichardson/db724faf7615f0ea208590a52da2c0eb to your computer and use it in GitHub Desktop.
S3 download promise: nodeJS promise to download file from amazon S3 to local destination
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
const AWS = require('aws-sdk'); | |
const fs = require('fs') | |
const s3download = (bucketName, keyName, localDest) => { | |
if (typeof localDest == 'undefined') { | |
localDest = keyName; | |
} | |
let params = { | |
Bucket: bucketName, | |
Key: keyName | |
} | |
let file = fs.createWriteStream(localDest) | |
return new Promise((resolve, reject) => { | |
s3.getObject(params).createReadStream() | |
.on('end', () => { | |
return resolve(); | |
}) | |
.on('error', (error) => { | |
return reject(error); | |
}).pipe(file) | |
}); | |
}; |
I think this the solution from @steima is the correct implementation, as for me I was using the 1st solution where the end
event came but does not mean the files were written, my next step which reads the files out, turns to be an incomplete file.
Same code but did some minor cleanups and adds missing import. @milesrichardson
var AWS = require('aws-sdk'); const fs = require('fs'); var s3 = new AWS.S3(); const s3download = (bucketName, keyName, localDest) => { if (typeof localDest == 'undefined') { localDest = keyName; } let params = { Bucket: bucketName, Key: keyName }; let file = fs.createWriteStream(localDest); return new Promise((resolve, reject) => { s3.getObject(params).createReadStream() .on('end', () => { return resolve(); }) .on('error', (error) => { return reject(error); }).pipe(file); }); };
A naive question: Why the resolve and reject is on read stream but not write stream? Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great solutiion