发表更新program3 分钟读完 (大约469个字) 利用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') var fs = require("fs"); var path = require("path");
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);
if(!fs.existsSync(localPath)){ throw new Error("本地目录"+ localPath + "不存在!") return }
var fileDic = new Array();
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/", }
|
阅读更多