-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
58 lines (48 loc) · 1.55 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
var Q = require('q');
var fs = require('fs');
var AWS = require('aws-sdk');
module.exports = function(result, options) {
if (!result) { result = {} };
var def = Q.defer();
if (!options) {
def.reject(new Error("S3 Download expected options to exist"));
} else if (!options.srcBucket) {
def.reject(new Error("S3 Download expected options.srcBucket to exist"));
} else if (!options.srcKey) {
def.reject(new Error("S3 Download expected options.srcKey to exist"));
} else if (!options.downloadFilepath) {
def.reject(new Error("S3 Download expected options.downloadFilepath to exist"));
} else {
for(var key in options) {
//TODO: unit test needs to enforce this
result[key] = options[key];
}
var params = {
Bucket: options.srcBucket,
Key: options.srcKey
};
var file = fs.createWriteStream(options.downloadFilepath)
if (options.region) {
var S3 = new AWS.S3({params: params, region: options.region});
} else {
var S3 = new AWS.S3({params: params});
}
var downloadProgress = 0;
var readStream = S3.getObject().createReadStream();
readStream.on('data', function(chunk) {
downloadProgress += chunk.length;
if (options.logLevel == 'debug') {
console.log('downloadProgress: ' + downloadProgress);
}
});
readStream.on('end', function() {
console.log('downloaded: ' + params.Key);
def.resolve(result);
});
readStream.on('error', function(err) {
def.reject(err);
});
readStream.pipe(file);
}
return def.promise;
}