import { NodeSSH } from "node-ssh";
import archiver from "archiver";
import { exec } from "child_process";
import { fileURLToPath } from "url";
import Client from "ssh2-sftp-client";
const __filename = fileURLToPath(import.meta.url); // 获取文件的绝对路径
const __dirname = path.dirname(__filename); // 获取目录名
const ssh = new NodeSSH();
const sftp = new Client();
host: "your server IP", // 服务器IP
username: "username", // 用户名
privateKey: "./private.pem", // 私钥
//password: "password", //
uploadPath: "/root/tmp/blog", // 文件上传临时目录
path: "/deploy/path", // 目标部署目录
async function buildProject() {
console.log("Building project...");
return new Promise((resolve, reject) => {
exec("pnpm build", (error, stdout, stderr) => {
console.error(`Build error: ${error.message}`);
console.error(`Build stderr: ${stderr}`);
return reject(new Error(stderr));
console.log(`Build stdout: ${stdout}`);
async function deleteLocalDist() {
console.log("Deleting local dist...");
return new Promise((resolve, reject) => {
exec("rm -rf shell/dist.zip", (error, stdout, stderr) => {
console.error(`Delete error: ${error.message}`);
console.error(`Delete stderr: ${stderr}`);
return reject(new Error(stderr));
console.log(`Deleted successfully`);
async function compressDist() {
console.log("Compressing dist directory...");
return new Promise((resolve, reject) => {
const output = fs.createWriteStream(path.join(__dirname, "dist.zip"));
const archive = archiver("zip", {
output.on("close", () => {
`dist.zip has been created. Total bytes: ${archive.pointer()}`,
archive.on("error", (err) => {
console.error(`Compression error: ${err.message}`);
archive.directory("dist/", true);
async function uploadToServer() {
console.log("Uploading dist.zip to server...");
username: serverConfig.username,
privateKey: fs.readFileSync(serverConfig.privateKey, "utf8"),
path.join(__dirname, "dist.zip"),
path.posix.join(serverConfig.uploadPath, "dist.zip"), // 使用 path.posix.join 处理路径
console.log("Upload complete.");
async function deploy() {
console.log("Connecting to server...");
username: serverConfig.username,
privateKey: fs.readFileSync(serverConfig.privateKey, "utf8"),
console.log("Removing old files...");
await ssh.execCommand(`rm -rf ${serverConfig.path}/*`);
console.log("Unzipping uploaded files...");
`unzip ${serverConfig.uploadPath}/dist.zip -d ${serverConfig.uploadPath}`,
console.log("Moving files to target directory...");
`mv ${serverConfig.uploadPath}/dist/* ${serverConfig.path}`,
console.log("Cleaning up...");
await ssh.execCommand(`rm -rf ${serverConfig.uploadPath}/dist`);
await ssh.execCommand(`rm ${serverConfig.uploadPath}/dist.zip`);
console.log("Deployment complete.");
console.error(`Deployment error: ${error.message}`);