index.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import Client from 'ssh2-sftp-client';
  2. import chalk from 'chalk';
  3. import ora from 'ora';
  4. import shell from 'shelljs';
  5. import path from 'path';
  6. import { fileURLToPath } from 'url';
  7. import { config } from './config.js';
  8. const rawArgv = process.argv.slice(2);
  9. const filterStage = rawArgv.includes("--prod") ? "prod" : "test";
  10. const __dirname = path.dirname(fileURLToPath(import.meta.url));
  11. // 构建
  12. const compileDist = async () => {
  13. console.log(chalk.blue("项目开始构建"));
  14. if (shell.exec(`npm run build:${filterStage}`).code === 0) {
  15. console.log(chalk.blue("项目构建成功"));
  16. }
  17. }
  18. // 获取配置
  19. const getConfig = () => {
  20. const [ result ] = config.filter(({ nodeEnv }) => nodeEnv === filterStage);
  21. return result;
  22. }
  23. // 部署
  24. const connectShell = async () => {
  25. const sftp = new Client();
  26. const item = getConfig();
  27. let spinner = null;
  28. // 打印信息
  29. const printMsg = ({ color, text }) => {
  30. console.log(chalk.red(`${item.host} --> `) + chalk[color](text));
  31. }
  32. printMsg({color: 'green', text: '服务器连接中'});
  33. sftp.connect({
  34. host: item.host,
  35. port: item.port,
  36. username: item.username,
  37. password: item.password,
  38. })
  39. .then(() => {
  40. console.log("item.path", item.path);
  41. printMsg({color: 'green', text: '服务器连接成功'});
  42. printMsg({color: 'yellow', text: '执行删除文件中'});
  43. return sftp.rmdir(item.path, true);
  44. })
  45. .then(() => {
  46. printMsg({color: 'green', text: '执行删除文件成功'});
  47. printMsg({color: 'green', text: '即将开始上传'});
  48. spinner = ora().start();
  49. spinner.text = '文件上传中,请等待'
  50. return sftp.uploadDir(path.resolve(__dirname, "../dist"), item.path);
  51. })
  52. .then(() => {
  53. spinner.info('文件上传结束')
  54. spinner.stop();
  55. printMsg({color: 'green', text: '上传完成,部署成功'});
  56. sftp.end();
  57. })
  58. .catch((err) => {
  59. console.error(
  60. err,
  61. chalk.red(`${item.host} -->`) + chalk.red(`上传失败`)
  62. );
  63. sftp.end();
  64. });
  65. }
  66. async function runStart() {
  67. await compileDist();
  68. await connectShell();
  69. }
  70. runStart();