publish.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import axios from 'axios';
  2. import archiver from 'archiver';
  3. import fs from 'fs';
  4. import path from 'path';
  5. import FormData from 'form-data';
  6. import { config } from './config';
  7. import urlJoin from 'url-join';
  8. /**
  9. * zip folder
  10. * sourceFolder,待压缩的文件夹
  11. * destZip,压缩后的zip文件
  12. * subdir,是否需要包一层
  13. */
  14. function zipFolder({ sourceFolder, destZip }) {
  15. // init
  16. return new Promise((resolve, reject) => {
  17. const output = fs.createWriteStream(destZip);
  18. const archive = archiver('zip', {
  19. zlib: { level: 9 },
  20. });
  21. console.log('zip 压缩中...');
  22. // on
  23. output.on('close', function () {
  24. console.log('zip压缩结束');
  25. resolve(null);
  26. });
  27. archive.on('error', function (err) {
  28. console.error('zip压缩失败', err);
  29. reject(err);
  30. });
  31. // zip
  32. archive.pipe(output);
  33. archive.directory(sourceFolder, false);
  34. archive.finalize();
  35. });
  36. }
  37. const getPath = (dir: string) => {
  38. return path.resolve(process.cwd(), dir);
  39. };
  40. const publish = async () => {
  41. const tempDestZipPath = getPath('tempDest.zip');
  42. console.log('destZipPath', tempDestZipPath);
  43. await zipFolder({
  44. sourceFolder: getPath(config.sourceFolder),
  45. destZip: tempDestZipPath,
  46. });
  47. const file = fs.createReadStream(tempDestZipPath);
  48. const formData = new FormData();
  49. formData.append('file', file);
  50. formData.append('dir', config.destFoler);
  51. console.log('开始上传', new Date().toLocaleString());
  52. axios
  53. .request({
  54. method: 'post',
  55. url: urlJoin(config.host, 'send'),
  56. data: formData,
  57. headers: {
  58. 'Content-Type': 'multipart/form-data',
  59. },
  60. })
  61. .catch((err) => {
  62. console.error('上传失败', err, new Date().toLocaleString());
  63. })
  64. .finally(() => {
  65. console.log('上传结束', new Date().toLocaleString());
  66. // 上传完要删除临时压缩包
  67. fs.unlinkSync(tempDestZipPath);
  68. });
  69. };
  70. publish();