-
-
Save gambitier/df110550a9a057056d7019a0fb086e20 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 hidden or 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) | |
| }); | |
| }; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
one of comment
A late answer but the problem is what at first glance seems as only a semantic error.
The Promise resolves on the end event of the read stream. This event is triggered when no more data can be read from the read stream. Meaning that the end of the read stream has been reached.
However, this does not necessarily mean, that all the data has already been written to disk in the example.
So the Promise should actually only resolve() once the write stream sends a finish event.