import superagent from 'superagent'; import mkdirp from 'mkdirp'; import path from 'path'; import fs from 'fs'; interface DownloadOptions { /** * 下载地址 */ link: string; /** * 下载本地目录 * @example * /project/path/demo.zip */ dist: string; } export interface DownloadResult { /** * 下载状态, stat为ok代表成功 */ stat: string; /** * 错误码 */ code: string; /** * 提示信息 */ message: string; } export default async function download(options: DownloadOptions): Promise { const { dist, link } = options; const dirname = path.dirname(options.dist); await mkdirp(dirname); return new Promise((resolve, reject) => { const stream = fs.createWriteStream(dist); const req = superagent.get(link).timeout({ response: 7000, // Wait 5 seconds for the server to start sending, deadline: 60000, // but allow 1 minute for the file to finish loading. }); req.on('error', function () { reject({ stat: 'fail', code: 'DOWNLOAD_ERROR', message: `下载资源失败: ${link}`, }); }); req.on('end', function () { stream.on('close', () => { resolve({ stat: 'ok', code: '', message: `下载成功: ${dist}`, }); }); }); req.pipe(stream); }); }