sftp-deploy-cfs
Version:
自动部署到sftp协议服务器的方式
112 lines (107 loc) • 3.67 kB
JavaScript
/**
* 将打包后的文件部署到服务器
* @author tanghaibo
*/
const scpClient = require('scp2');
const ora = require('ora');
const chalk = require('chalk');
const path = require('path');
const fs = require('fs');
// 是否通过命令参数指定执行的服务器id?多个用","分割。比如:npm run deploy sit,uat 则代表部署到id=sit与id=uat的服务器
let execIdArr;
if (process.argv.length > 2) {
execIdArr = process.argv[2].split(',')
}
/**
* 部署
* @param {Array} serverList 服务器相关配置
* serverList示例:
* [{
* id: 'uat', // 唯一key
* name: 'UAT环境', // 别名
* host: '10.6.14.138', // 服务器ip
* port: 23, // 端口
* username: '****', // 服务器账号
* password: '****', // 服务器密码
* deployPath: 'dist', // 待部署的文件路径
* romotePath: '/host1' // 部署到服务器的文件路径
* }, ...
*]
* @param {String} fullPath 指向工程下根目录的全路径
*/
function deploy (serverList = [], fullPath = path.resolve('./')) {
// 部署前的相关处理
deployBefore(serverList)
// 遍历所有服务器
serverList.forEach((serverOp) => {
// 如果execIdArr有值(没值就全部服务器都部署),并且在execIdArr中找不到serverOp['id'],则当前serverOp对应的服务器不进行部署
if (execIdArr && execIdArr.length > 0 && !execIdArr.find(id => serverOp['id'] === id)) {
return;
}
const deployFullPath = path.resolve(fullPath, serverOp.deployPath)
if (isEmptyDir(deployFullPath)) {
let err = deployFullPath + '为空目录!'
console.log(chalk.red(`Error!${serverOp.name}(${serverOp.id})服务器部署失败.`), err);
return;
}
const startTime = +new Date()
console.log('开始部署', serverOp.id)
const spinner = ora(`正在部署到${serverOp.name}(${serverOp.id})服务器...\n`);
spinner.start();
scpClient.scp(
deployFullPath,
{
host: serverOp.host,
port: serverOp.port,
username: serverOp.username,
password: serverOp.password,
path: serverOp.romotePath,
readyTimeout: 1000 * 20 // 超时时间
},
function (err) {
spinner.stop();
console.log(serverOp.name, `用时${+new Date() - startTime}ms`)
if (err) {
console.log(chalk.red(`Error!${serverOp.name}(${serverOp.id})服务器部署失败.`), err);
} else {
console.log(chalk.green(`Success! 成功部署到${serverOp.name}(${serverOp.id})服务器! \n`));
}
}
);
});
}
/**
* 部署前的相关处理
*/
function deployBefore (serverList) {
// 是否指定执行的服务器id
if (execIdArr) {
console.log('已指定即将部署的服务器对应的id:', execIdArr)
let notExistArr = [] // 在指定的id中,获取不存在的集合
execIdArr.forEach(id => {
if(!serverList.find(s => s['id'] === id)) notExistArr.push(id)
})
if (notExistArr && notExistArr.length) {
let err = `指定的服务器id不存在:${notExistArr}`;
throw err
}
} else {
console.log(`未指定即将部署服务器的id,将部署到所有服务器`)
}
}
/**
* 判断是否为空目录
* @param {String} path
* @returns {Boolean} true=空目录
*/
function isEmptyDir(path) {
// 获取所有文件及目录
const files = fs.readdirSync(path);
// 判断是否空
if (!files || !files.length) {
return true // 空目录
} else {
return false
}
}
module.exports = deploy