-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
123 lines (111 loc) · 2.9 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
117
118
119
120
121
122
123
var fs = require('fs')
var path = require('path')
var gutil = require('gulp-util')
var through2 = require('through2')
var assign = require('object-assign')
var Q = require('q')
var COS = require('cos-nodejs-sdk-v5')
var log = gutil.log
var colors = gutil.colors
module.exports = function (config) {
config = config || {}
config = assign({
AppId: '',
SecretId: '',
SecretKey: '',
Bucket: '',
Region: '',
Prefix: '',
OverWrite: false,
Headers: false
}, config)
if (config.Bucket.indexOf('-') === -1) {
config.Bucket += '-' + config.AppId
}
var existFiles = 0
var uploadedFiles = 0
var uploadedFail = 0
var tasks = []
var cos = new COS({
SecretId: config.SecretId,
SecretKey: config.SecretKey
})
return through2.obj(function (file, enc, cb) {
if (file.isNull()) {
return cb()
}
var filePath = file.path
var fileKey = path.join(config.Prefix, path.relative(file.base, file.path))
var handler = function () {
var defer = Q.defer()
upload()
function check (callback) {
var defer = Q.defer()
cos.headObject({
Bucket: config.Bucket,
Region: config.Region,
Key: fileKey
}, function (err, data) {
if (err) {
callback(false)
} else {
log('Exist ' + fileKey)
callback(200 == data.statusCode)
}
})
return defer.promise
}
function putFile () {
let obj = assign(config.Headers || {}, {
Bucket: config.Bucket,
Region: config.Region,
Key: fileKey,
ContentLength: fs.statSync(filePath).size,
Body: fs.createReadStream(filePath),
onProgress (progressData) {
// console.log(progressData)
}
})
cos.putObject(obj, function (err, data) {
if (err) {
uploadedFail++
log('err-putObject', err)
defer.reject()
} else {
uploadedFiles++
log(colors.green('Upload ' + fileKey + ' Success'))
defer.resolve()
}
})
}
function upload () {
var uploadFlag = true
if (!config.OverWrite) {
check(function (status) {
if (status) {
existFiles++
defer.resolve()
} else {
putFile()
}
})
} else {
putFile()
}
}
return defer.promise
}
tasks.push(handler())
cb()
}, function () {
Q.allSettled(tasks)
.then(function (fulfilled) {
log('Upload to qcloud: Total:', colors.green(fulfilled.length),
'Skip:', colors.gray(existFiles),
'Upload:', colors.green(uploadedFiles),
'Failed:', colors.red(uploadedFail))
}, function (err) {
log('Failed upload files:', err)
})
})
}