| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- import axios from 'axios';
- import archiver from 'archiver';
- import fs from 'fs';
- import path from 'path';
- import FormData from 'form-data';
- import { config } from './config';
- import urlJoin from 'url-join';
- /**
- * zip folder
- * sourceFolder,待压缩的文件夹
- * destZip,压缩后的zip文件
- * subdir,是否需要包一层
- */
- function zipFolder({ sourceFolder, destZip }) {
- // init
- return new Promise((resolve, reject) => {
- const output = fs.createWriteStream(destZip);
- const archive = archiver('zip', {
- zlib: { level: 9 },
- });
- console.log('zip 压缩中...');
- // on
- output.on('close', function () {
- console.log('zip压缩结束');
- resolve(null);
- });
- archive.on('error', function (err) {
- console.error('zip压缩失败', err);
- reject(err);
- });
- // zip
- archive.pipe(output);
- archive.directory(sourceFolder, false);
- archive.finalize();
- });
- }
- const getPath = (dir: string) => {
- return path.resolve(process.cwd(), dir);
- };
- const publish = async () => {
- const tempDestZipPath = getPath('tempDest.zip');
- console.log('destZipPath', tempDestZipPath);
- await zipFolder({
- sourceFolder: getPath(config.sourceFolder),
- destZip: tempDestZipPath,
- });
- const file = fs.createReadStream(tempDestZipPath);
- const formData = new FormData();
- formData.append('file', file);
- formData.append('dir', config.destFoler);
- console.log('开始上传', new Date().toLocaleString());
- axios
- .request({
- method: 'post',
- url: urlJoin(config.host, 'send'),
- data: formData,
- headers: {
- 'Content-Type': 'multipart/form-data',
- },
- })
- .catch((err) => {
- console.error('上传失败', err, new Date().toLocaleString());
- })
- .finally(() => {
- console.log('上传结束', new Date().toLocaleString());
- // 上传完要删除临时压缩包
- fs.unlinkSync(tempDestZipPath);
- });
- };
- publish();
|