oss-released.js
2.98 KB
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
/**
* Created by pc on 2018/5/11.
* 需要的库为(co, ali-oss, glob)
* npm i co ali-oss glob --save
* ossConfig.json格式如下
{
"region": "oss-cn-shanghai", //OSS region
"accessKeyId": "XXXXXXXX", //OSS accessKeyId
"accessKeySecret": "XXXXXXXX", //OSS accessKeySecret
"bucket": "ogo", //OSS bucket
"localPath": "./dist/**", //本地需要上传的文件目录,(/**)为遍历根号后所有目录
"ossPath": "/mobile/", //oss线上文件目录(不能为根目录,避免误操作,最后加上'/')
"callbackUrl": "http://nodejs.org/dist/index.json" //预留请求服务器更新缓存的API
}
*
*
*/
let co = require('co')
let OSS = require('ali-oss')
let glob = require('glob')
let http = require('http')
let Config = require('./ossConfig.json')
// 配置oss信息
let client = new OSS({
region: Config.region,
accessKeyId: Config.accessKeyId,
accessKeySecret: Config.accessKeySecret,
bucket: Config.bucket
})
// 删除线上目录
function deleteFiles() {
if (Config.ossPath !== '' && Config.ossPath !== '/') {
co(function* () {
let result = yield client.list({
prefix: Config.ossPath.slice(1, -1),
marker: Config.ossPath.slice(0, -1)
})
let index = 0
if (result.objects !== undefined) {
yield result.objects.map(i => {
co(function* () {
yield client.delete(i.name)
index += 1
if (index === result.objects.length) {
console.log(`全部删除成功~,总共${result.objects.length}个文件`)
uploadFiles()
}
})
})
} else {
uploadFiles()
}
}).catch(function (err) {
console.log(err)
})
} else {
console.error('上传失败,线上路径为根目录~')
}
}
function uploadFiles() {
// 遍历目录树之后上传
glob(Config.localPath, {
nodir: true
}, (er, files) => {
let index = 0
files.map(i => {
co(function* () {
let ossPath = Config.ossPath.substr(Config.ossPath.length - 1, 1) === '/' ? Config.ossPath.slice(0, -1) : Config.ossPath
yield client.put(ossPath + i.slice(6), i)
index += 1
if (index === files.length) {
consoleStr(files.length)
}
}).catch(function (err) {
console.error(err.params.object)
})
})
})
}
function consoleStr(length) {
console.log(`全部上传成功~,总共${length}个文件`)
// http.get(Config.callbackUrl, () => {
// console.log('更新缓存成功~')
// }).on('error', (e) => {
// console.error(`错误: ${e.message}`)
// })
}
// 清空目录后上传
// deleteFiles()
// 增量上传
uploadFiles()