前端项目手动部署的话既麻烦又Low, 而CI又太复杂。通过SCP2,可以实现简单轻量化的一键自动部署。
const scpClient = require('scp2') //引入scp2
const path = require('path')
//服务器配置信息
let config = {
dev: {
host: '', // 服务器地址ip
port: '22', // 服务器端口
username: '',
password: '',
path: '' //网站的服务器根路径
}
}
const hostInfo = config.dev
//封装scp连接函数
function scpFn(dir) {
return new Promise((resolve, reject) => {
try {
scpClient.scp(
dir,//要上传的文件路径
{
host: hostInfo.host,
port: hostInfo.port,
username: hostInfo.username,
password: hostInfo.password,
path: `${hostInfo.path}/${dir}`
},
function (err) {
if (err) {
console.log(err);
console.log(`${dir}发布失败.\n`)
} else {
console.log(`${dir}发布成功!\n`)
}
resolve()
}
)
} catch (error) {
console.log(error)
}
})
}
//遍历要上传的文件
async function eachScp() {
const dirs = ['index.html','static']
const promiseAll = dirs.map((dir) => {
return scpFn(dir)
})
await Promise.all(promiseAll)
// await scpFn('index.html')
console.log(`最终发布完成!\n`)
}
// 如果没有密码 进行输入
if (hostInfo && !hostInfo.password) {
const readline = require('readline')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
// 监听键入回车事件
rl.question('请输入密码:', (pwd) => {
rl.close()
hostInfo.password = pwd.trim()
eachScp()
})
} else if (hostInfo) {
eachScp() //上传文件
}