const client = require("ssh2-sftp-client"); const path = require("path"); const fs = require("fs"); const { execSync } = require("child_process"); (async function Init() { const localDir = "dist/"; const dirPath = path.resolve(__dirname, "./" + localDir); const list = []; /** * 获取localDir下的所有文件路径 * @param {string} pathDir */ async function getFiles(pathDir) { const dirList = fs.readdirSync(pathDir) || []; for (let i = 0; i < dirList.length; i++) { const P = [pathDir, dirList[i]]; const stat = fs.lstatSync(P.join("\\")); if (!stat.isDirectory()) { list.push(P); } else getFiles(P.join("\\")); } } async function upServer() { const config = { path: { // 远程地址 romotePath: "/var/www/test", // 本地地址 localPath: path.resolve(__dirname, "./dist"), }, romote: { // 服务器 ip 地址 host: "123.57.195.226", // 端口号,默认是 22 port: 22, // 登录的用户名 username: "root", // 登录密码 password: "581100Li.", }, }; const sftp = new client(); try { await sftp.connect(config.romote); const isCss = sftp.exists(config.path.romotePath + "/css"); const isFonts = sftp.exists(config.path.romotePath + "/fonts"); const isJs = sftp.exists(config.path.romotePath + "/js"); const isIndexHtml = sftp.exists(config.path.romotePath + "/index.html"); isCss && await sftp.rmdir(config.path.romotePath + "/css", true); isFonts && await sftp.rmdir(config.path.romotePath + "/fonts", true); isJs && await sftp.rmdir(config.path.romotePath + "/js", true); isIndexHtml && await sftp.delete(config.path.romotePath + "/index.html", true); console.log("已清空原有文件"); await sftp.uploadDir(config.path.localPath, config.path.romotePath); console.log("上传完成"); // 断开连接 sftp.end(); console.log("断开链接"); } catch (err) { console.log("更新失败", err); } } /** * 上传git */ function execFun() { try { execSync("git add ."); execSync('git commit -m "提交"'); execSync("git push"); console.log("上传git---完成"); } catch (e) { console.log("上传git---失败"); console.error(e); } } try { execFun(); await getFiles(dirPath); console.log("获取文件路径---完成"); await upServer(); } catch (err) { console.log("数据上传oss---失败"); } })();