前言
前端項目部署時,nginx配置完成后,只需將打包后的文件上傳至服務器指定目錄下便可。 前端
通常使用如下方式完成:node
- xshell 等命令行工具上傳
- ftp/sftp 等可視化工具上傳
- jenkins 等自動化部署服務 對於簡單前端項目,頻繁部署時,xshell、ftp兩種方式較為繁瑣,而jenkins 等自動化部署服務須要提早安裝軟件、並熟悉配置流程。 所以但願借助本地 node 服務實現對前端打包后文件的上傳工做,既不須要服務器額外安裝程序,還能夠幫助咱們實現快速上傳部署,更能幫助咱們深刻了解 node 。
目的
減小web項目在開發調試過程當中頻繁編譯打包后再使用ftp工具部署至服務器的手動過程,提升工做效率。nginx
1.導入依賴模塊
- npm install inquirer ssh2-sftp-client
- touch ssh.js helper.js
- 在package.json增長一個腳本,完成以后必定要 npm i 從新安裝依賴,確保新加入的腳本生效!
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"deploy": "bash deploy.sh"
},
- touch deploy.sh
npm run build echo "打包完成" node ./ssh.js cd -
2. 鏈接遠端服務器並上傳操做
const Client = require('ssh2-sftp-client')
const sftp = new Client()
const helper = require ('./helper')
const config = [
{
name: 'a', // 項目/服務器名稱
ssh: {
host: '192.168.0.105',
port: 22,
username: 'root',
password: 'root',
},
romotePath: '/var/www/dist',// 遠程地址
localPath:'./dist',// 本地地址
},
{
name: 'b',
ssh: {
host: '192.168.0.110',
port: 22,
username: 'root',
password: 'root',
},
romotePath: '/var/www/dist',
localPath:'./dist',
}
]
async function main() {
const SELECT_CONFIG = (await helper(config)).value // 所選部署項目的配置信息
console.log('您選擇了部署 ' + SELECT_CONFIG.name)
sftp
.connect(SELECT_CONFIG.ssh)
.then(() => {
console.log('- 鏈接成功,上傳中..')
return sftp.uploadDir(SELECT_CONFIG.localPath, SELECT_CONFIG.romotePath)
})
.then(data => {
console.log(data,' 上傳完成,及時清除緩存' )
})
.catch(err => {
console.log(err,' 出錯了!快看看怎么回事! ')
})
.finally(() => {
sftp.end()// 斷開鏈接
})
}
main()
3.構建和發布
- 執行 npm run deploy 就能夠打包並主動上傳到你的目標服務器
- windows系統 Git Bash Use arrow keys沒法選擇
winpty npm.cmd run deploy
