-
Notifications
You must be signed in to change notification settings - Fork 141
/
qiniu.js
67 lines (58 loc) · 2.25 KB
/
qiniu.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
const qiniu = require("qiniu")
const glob = require('glob')
const crypto = require('crypto-js')
const qiniuIO = qiniu.io
const qiniuRs = qiniu.rs
const qiniuRsf = qiniu.rsf
const client = new qiniuRs.Client()
class Qiniu {
constructor(accessKey, secretKey) {
this.accessKey = accessKey
this.secretKey = secretKey
this.bucket = 'mvc-linesh-tw'
qiniu.conf.ACCESS_KEY = this.accessKey.toString(crypto.enc.Utf8)
qiniu.conf.SECRET_KEY = this.secretKey.toString(crypto.enc.Utf8)
}
uploadFiles(uploadingPath, options) {
console.log('---------------------------')
glob.sync(uploadingPath, {
nodir: options.nodir,
ignore: options.ignoringList
}).forEach(filepath => {
const resourceKey = filepath.substring(options.strippedPath.length, filepath.length)
// ':' means allow override upload. For further details refer to offical API docs
const policyToken = new qiniuRs.PutPolicy(this.bucket + ":" + resourceKey).token()
uploadFileInternal(policyToken, resourceKey, filepath)
})
}
clearBucket() {
console.log('---------------------------')
qiniuRsf.listPrefix(this.bucket, '', '', '', '', (error, response) => {
if (error) {
errorLog('listing all resource in bucket', this.bucket, error)
return ;
}
console.log('Listing all resources currently in qiniu bucket: ')
console.log(response.items.map(item => item.key))
response.items.map(item => item.key).forEach(resource => {
client.remove(this.bucket, resource, (error) => {
console.log('[Delete] Origin resource removed successfully: ' + resource)
})
})
})
}
}
function uploadFileInternal(uptoken, key, file) {
qiniuIO.putFile(uptoken, key, file, new qiniuIO.PutExtra(), (error, response) => {
if (error) {
errorLog('uploading file', response.key, error)
return ;
}
console.log('[Success] File uploaded to 七牛: ' + response.key)
})
}
function errorLog(event, resource, error) {
console.error('[error] Something went wrong when ' + event + ': ' + resource + '. Error message dumped below:')
console.error(error)
}
module.exports = Qiniu