利用nodejs在webpack打包完成后自动上传文件到阿里云OSS

项目使用Webpack打包,打包完成后生成一些asset,不管是本地开发还是jenkins持续集成,都希望自动上传这些asset到阿里云OSS,于是用nodejs写一个脚本:

1. upload_oss.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
68
69
70
71
72
73
74
75
76
77
78
79
80
var co = require('co'); 
var OSS = require('ali-oss') //阿里云oss模块
var fs = require("fs"); //文件模块
var path = require("path");

//---------------------------使用说明----------------------------
//获取命令行传入参数(第0个参数是node 第1个参数是js文件 第2个文件是本地文件夹路径 第3个是oss相对目录)
//命令格式举例: node oss/upload_oss.js ../../static/ /static/

var localPath = process.argv[2]
var remotePath = process.argv[3]
if(localPath == null || remotePath == null){
throw new Error("缺少目录参数!");
return
}

localPath = path.resolve(localPath); //本地目录
remotePath = path.resolve(remotePath); //OSS相对目录

if(!fs.existsSync(localPath)){
throw new Error("本地目录"+ localPath + "不存在!")
return
}


//上传列表
var fileDic = new Array();

//阿里云OSS配置
var client = new OSS({
region: 'oss-cn-shenzhen',
accessKeyId: 'xxxx',
accessKeySecret: 'xxxx',
bucket: 'xxxx'
});



console.log('---------上传OSS---------');
console.log('【Step1】 分析目录');

readDir(localPath)

function readDir(filePath){
filePath = path.resolve(filePath);
//遍历文件目录
var pa = fs.readdirSync(filePath);
pa.forEach(function(filename,index){
var file = path.join(filePath,filename)
var info = fs.statSync(file)
//目录
if(info.isDirectory()){
readDir(file);
}
//文件
else {
//添加到上传列表
var localDir = path.join(filePath,filename);
var remoteDir = path.join(remotePath, localDir.replace(localPath,""));
fileDic[localDir] = remoteDir;
console.log("add file:" + localDir)
}
})
}

console.log('【Step2】 上传文件');

co(function* () {
for(var localDir in fileDic)
{
var result = yield client.put(fileDic[localDir], localDir);
console.log("upload from '" + localDir + "' to '" + fileDic[localDir] + "'");
}
console.log('【Step3】 完成');
}
).catch(function (err) {
throw new Error(err);
}
);

2. package.json调用

1
2
3
4
5
"scripts": {
"dev": "webpack-dev-server --devtool inline-source-map --progress --color --watch-poll",
"test": "export NODE_ENV=test && webpack --progress --color && node oss/upload_oss.js ../test_static/ /demo/test_static/",
"prod": "export NODE_ENV=production && webpack --progress --color && node oss/upload_oss.js ../static/ /demo/static/",
}

如上所示:

  • test环境下,上传本地test_static文件夹到OSS的demo/test_static
  • prod环境下,上传本地static文件夹到OSS的demo/static

利用nodejs在webpack打包完成后自动上传文件到阿里云OSS

https://wurang.net/webpack_upload_to_alioss/

作者

Wu Rang

发布于

2017-10-25

更新于

2021-12-06

许可协议

评论