chore: basic 从pipeline中移除

This commit is contained in:
xiaojunnuo
2024-11-04 15:14:56 +08:00
parent 0f572f4cb3
commit 1274f56da8
38 changed files with 128 additions and 58 deletions

View File

@@ -8,7 +8,7 @@ export * from './util.hash.js';
export * from './util.merge.js';
export * from './util.cache.js';
import sleep from './util.sleep.js';
import { http } from './util.request.js';
import { http, download } from './util.request.js';
import { mergeUtils } from './util.merge.js';
import { sp } from './util.sp.js';
@@ -25,6 +25,7 @@ import * as id from './util.id.js';
export const utils = {
sleep,
http,
download,
sp,
hash: hashUtils,
promises,

View File

@@ -6,6 +6,8 @@ import { HttpsProxyAgent } from 'https-proxy-agent';
import nodeHttp from 'http';
import * as https from 'node:https';
import { merge } from 'lodash-es';
import { safePromise } from './util.promise';
import fs from 'fs';
export class HttpError extends Error {
status?: number;
statusText?: string;
@@ -214,3 +216,38 @@ export function createAgent(opts: CreateAgentOptions = {}) {
httpsAgent,
};
}
export async function download(http: HttpClient, config: HttpRequestConfig, savePath: string) {
return safePromise((resolve, reject) => {
http
.request({
...config,
responseType: 'stream',
})
.then(res => {
const writer = fs.createWriteStream(savePath);
res.data.pipe(writer);
writer.on('close', () => {
console.log('文件下载成功');
resolve(true);
});
//error
writer.on('error', err => {
console.error('下载失败', err);
reject(err);
});
//进度条打印
const totalLength = res.headers['content-length'];
let currentLength = 0;
res.data.on('data', (chunk: any) => {
currentLength += chunk.length;
const percent = ((currentLength / totalLength) * 100).toFixed(2);
console.log(`下载进度:${percent}%`);
});
})
.catch(err => {
console.error('下载失败', err);
reject(err);
});
});
}