UNPKG

comic-book-dl

Version:
48 lines (47 loc) 1.6 kB
import { pipeline } from 'node:stream/promises'; import { createWriteStream } from 'node:fs'; import got from '../../../../node_modules/got/dist/source/index.js'; import pLimit from 'p-limit'; import { UA, getUrlFileName } from '../../../utils/index.js'; export class Base { constructor(bookUrl) { this.type = 'base'; this.bookUrl = bookUrl ?? ''; } genReqOptions() { return { headers: { 'user-agent': UA } }; } async saveImgList(path, imgList, saveImgCallback) { const limit = pLimit(6); const promiseList = imgList.map(imgUrl => limit(async () => { let isSuccess = true; let imgFileName = ''; try { imgFileName = await this.saveImg(path, imgUrl); } catch (err) { isSuccess = false; } if (typeof saveImgCallback === 'function') saveImgCallback(imgUrl, isSuccess); return imgFileName; })); return await Promise.all(promiseList); } async saveImg(path, imgUrl, fixFileName, fixSuffix) { if (!imgUrl) return ''; let imgName = getUrlFileName(imgUrl) ?? ''; imgName = decodeURIComponent(imgName); if (fixFileName) { const suffix = imgName?.split('.')?.[1] ?? 'jpg'; imgName = `${fixFileName}.${fixSuffix ?? suffix}`; } await pipeline(got.stream(imgUrl, this.genReqOptions()), createWriteStream(`${path}/${imgName}`)); return imgName; } }