起因
最近在用nuxt做一個專案,沒有找到nuxt
檔案上傳cos
的
nuxt+pm2 自動化部署及打包後檔案自動上傳阿里雲 oss的是oss
,
可惜我用的是cos
,於是根據它修改成了cos
新建cosUpload.js
cnpm i cos-nodejs-sdk-v5 --save
cnpm i dotenv
const dotenv = require("dotenv")
dotenv.config()
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
SecretId=
SecretKey=
Bucket=
Region=
UploadPath=view //上傳到cos那個路徑
執行
node cosUpload.js
本作品採用《CC 協議》,轉載必須註明作者和本文連結