avatar

Catalog
将nuxt打包文件上传到腾讯云cos

起因

最近在用nuxt做一个项目,没有找到nuxt文件上传cos

nuxt+pm2 自动化部署及打包后文件自动上传阿里云 oss的是oss,

可惜我用的是cos,于是根据它修改成了cos

新建cosUpload.js

Code
1
2
cnpm i cos-nodejs-sdk-v5 --save
cnpm i dotenv
Code
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
  const dotenv = require("dotenv")
dotenv.config()

//把静态文件上传到腾讯云cos
const Cos = require("cos-nodejs-sdk-v5");

const fs = require("fs");
const path = require("path");

const os = require("os");

const PUBLIC_PATH = path.join(__dirname, "/");

const client = new Cos({
SecretId: process.env.SecretId,
SecretKey: process.env.SecretKey
});

async function deleteDir(dir) {
let result = await client.getBucket({
Bucket: process.env.Bucket, /* 必须 */
Region: process.env.Region,
Prefix: dir + "/",
},async function (err,result){
if (result.Contents) {
let keys = [];
result.Contents.forEach(function(obj) {
keys.push({"Key":obj.Key});
});

try {
await client.deleteMultipleObject( {
Bucket: process.env.Bucket, /* 必须 */
Region: process.env.Region,
Objects: keys
});
successMes('cos删除'+ dir +'成功')
} catch (e) {
console.log("文件删除失败", e);
}
}

});

}



function addFileToCosSync(src, dist) {
let docs = fs.readdirSync(src);

docs.forEach(function(doc) {
let _src = src + "/" + doc,
_dist = dist + "/" + doc;
let st = fs.statSync(_src);
// 判断是否为文件
if (st.isFile() && doc !== ".DS_Store") {
putCos(_src, _dist);
}
// 如果是目录则递归调用自身
else if (st.isDirectory()) {
addFileToCosSync(_src, _dist);
}
});

}

/** *单个文件上传至cos */
async function putCos(src, dist) {

await client.putObject({
Bucket: process.env.Bucket, /* 必须 */
Region: process.env.Region,
Key: dist, /* 必须 */
Body: fs.createReadStream(src),
},function(err,data){
successMes(src + ' 上传成功')
if( err != null)
console.log(" 上传失败".err);
})

}

/** *上传文件启动 *@param {string} dirName 将要上传的文件名 */
async function upFile(dirName) {
try {
await deleteDir(dirName);
await addFileToCosSync(PUBLIC_PATH + ".nuxt/dist/client", dirName);

} catch (err) {
console.log(dirName + "上传cos成功失败", err);
}}

function successMes(msg)
{
console.log('\u001b[32m '+ msg +'\u001b[0m');
}

upFile(process.env.UploadPath);

新建.env

Code
1
2
3
4
5
6

SecretId=
SecretKey=
Bucket=
Region=
UploadPath=view //上传到cos那个路径

运行

node cosUpload.js

http://cdn.lblog.club/images/node_cos_upload.png

Author: xxh
Link: http://lblog.club/2020/03/30/node_cos/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.

Comment