NodeSSH一键部署
简述
如果没有选择托管网站而是在自有服务器上建设网站,那就只能自己手写一个部署脚本了。Node SSH简洁高效,十分方便。
安装
sh
$ npm install node-ssh
脚本文件
新建js文件(如autoDeploy\ssh.js)
js
import path from 'path'
import { NodeSSH } from 'node-ssh'
const ssh = new NodeSSH()
ssh.connect({
host: '********',
username: '****',
privateKeyPath: 'D:\\****\\***.pem',
port: ***
}).then(function () {
// Command 删除旧文件
ssh.execCommand('rm -rf /usr/local/nginx/html/*', { cwd: '/usr/local/nginx/html' }).then(function (result) {
console.log('STDOUT: ' + result.stdout)
console.log('STDERR: ' + result.stderr)
})
// Putting entire directories 上传新文件
const failed = []
const successful = []
ssh.putDirectory('D:\\****\\docs\\.vitepress\\dist', '/usr/local/nginx/html', {
recursive: true,
concurrency: 10,
// ^ WARNING: Not all servers support high concurrency
// try a bunch of values and see what works on your server
validate: function (itemPath) {
const baseName = path.basename(itemPath)
return baseName.substring(0, 1) !== '.' && // do not allow dot files
baseName !== 'node_modules' // do not allow node_modules
},
tick: function (localPath, remotePath, error) {
if (error) {
failed.push(localPath)
} else {
successful.push(localPath)
}
}
}).then(function (status) {
console.log('the directory transfer was', status ? 'successful' : 'unsuccessful')
console.log('successful transfers', successful.length)
console.log('failed transfers', failed.join(', '))
process.exit(1)
})
})
定义命令
在package.json的scripts定义脚本命令
json
{
"type": "module",
"devDependencies": {
//...
},
"scripts": {
"docs:dev": "vitepress dev docs",
"docs:build": "vitepress build docs",
"docs:preview": "vitepress preview docs",
"bd": "node autoDeploy/ssh.js"
},
"dependencies": {
//...
}
}
&&可以顺序连接两个命令,如先构建再部署:
json
{
"scripts": {
"bd": "vitepress build docs&&node autoDeploy/ssh.js"
},
}
使用
运行已定义的命令即可一键部署至服务器
sh
$ npm run bd
2025-03-19