-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
62 lines (59 loc) · 2.48 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
var path = require('path');
var through2 = require('through2');
var colors = require('gulp-util').colors;
var log = require('gulp-util').log;
var Moment = require('moment');
var Q = require('q');
var fs = require('fs');
var util = require('util');
var crypto = require('crypto');
var existFiles = 0;
var uploadedFiles = 0;
var uploadedFail = 0;
var qcloud = require('qcloud_cos');
module.exports = function(cloud, option) {
option = option || {};
option = Object.assign({}, { dir: '', prefix: '' }, option);
var version = Moment().format('YYMMDDHHmm'),
tasks = [];
return through2.obj(function(file, enc, next) {
var that = this;
if (file._contents === null) return next();
var filePath = path.relative(file.base, file.path);
var fileKey = option.dir + ((!option.dir || option.dir[option.dir.length - 1]) === '/' ? '' : '/') + filePath.split(path.sep).join('/');
var prefixFileKey = (option.prefix) === '' ? fileKey : (option.prefix + ((!option.prefix || option.prefix[option.prefix.length - 1]) === '/' ? '' : '/') + filePath.split(path.sep).join('/'));
qcloud.conf.setAppInfo(cloud.appid, cloud.secretId, cloud.accessId);
var handler = function() {
var defer = Q.defer();
qcloud.cos.statFile(cloud.bucket, prefixFileKey, function(ret) {
if (ret.code === 0) {
existFiles++;
return defer.resolve();
}
uploadedFiles++;
qcloud.cos.upload(fileKey, cloud.bucket, prefixFileKey, 1, function(ret) {
log('Start →', colors.green(prefixFileKey), '→', ret.message);
if (ret.code != 0) {
uploadedFail++;
log('Error →', colors.red(prefixFileKey), ret.message);
defer.reject();
}
defer.resolve();
});
});
return defer.promise;
};
tasks.push(handler());
next();
}, function() {
Q.allSettled(tasks)
.then(function(fulfilled) {
log('共处理:', colors.green(fulfilled.length),
'跳过:', colors.gray(existFiles),
'上传:', colors.green(uploadedFiles - uploadedFail),
'失败:', colors.red(uploadedFail));
}, function(err) {
log('Failed upload files:', err.message);
});
});
};