-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
116 lines (101 loc) · 2.52 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
'use strict';
const fs = require('fs');
const path = require('path');
const AWS = require('aws-sdk');
const mime = require('mime-types');
const Emitter = require('events');
const glob = require('glob');
const recursive = require('recursive-readdir');
const bytes = require('bytes');
function Uploader(options) {
Emitter.call(this);
this.acl = options.acl;
this.verbose = options.verbose;
this.prefix = options.prefix;
this.bucket = options.bucket;
this.pending = 0;
this.totalBytes = 0;
this.totalFiles = 0;
this.uploadedBytes = 0;
this.uploadedFiles = 0;
this.root = path.resolve(process.cwd());
var opts = {
apiVersion: '2006-03-01'
};
if (options.region) {
opts.region = options.region;
}
this.s3 = new AWS.S3(opts);
this.failed = false;
this.on('error', function(err) {
this.failed = err;
}.bind(this));
this.on('file', function(file, buffer, root) {
this.upload(file, buffer, root);
}.bind(this));
}
Uploader.prototype = new Emitter();
Uploader.prototype.addPattern = function(pattern) {
var options = {
cwd: this.root
};
glob(pattern, options, function(err, files) {
if (err) {
this.emit('error', err);
} else {
files.forEach(readFile(this.root), this);
}
}.bind(this));
};
Uploader.prototype.addDirectory = function(dir) {
var root = path.resolve(this.root, dir);
recursive(root, function(err, files) {
if (err) {
this.emit('error', err);
} else {
files.forEach(readFile(root), this);
}
}.bind(this));
};
Uploader.prototype.upload = function(file, buffer, root) {
var key = file.split(root + '/').pop();
if (this.failed) {
return;
}
this.pending += 1;
this.totalBytes += buffer.byteLength;
this.totalFiles += 1;
var options = {
ACL: this.acl,
Bucket: this.bucket,
Key: this.prefix + key,
Body: buffer,
ContentType: mime.contentType(path.extname(file)) || 'application/octet-stream'
};
this.s3.putObject(options, function(err, data) {
this.pending -= 1;
if (err) {
this.emit('error', err);
return;
}
this.uploadedBytes += buffer.byteLength;
this.uploadedFiles += 1;
if (this.pending === 0) {
this.emit('end');
} else {
this.emit('progress');
}
}.bind(this));
};
function readFile(root) {
return function(file) {
fs.readFile(file, function(err, buffer) {
if (err) {
this.emit('error', err);
} else {
this.emit('file', file, buffer, root);
}
}.bind(this));
};
}
module.exports = Uploader;