1
0
mirror of https://github.com/hotomoe/hotomoe synced 2024-12-18 00:28:16 +09:00
hotomoe/src/misc/download-url.ts

40 lines
1.1 KiB
TypeScript
Raw Normal View History

import * as fs from 'fs';
import * as stream from 'stream';
import * as util from 'util';
import fetch from 'node-fetch';
import { httpAgent, httpsAgent } from './fetch';
import { AbortController } from 'abort-controller';
import config from '../config';
2019-11-24 17:09:32 +09:00
import * as chalk from 'chalk';
import Logger from '../services/logger';
const pipeline = util.promisify(stream.pipeline);
export async function downloadUrl(url: string, path: string) {
2019-07-01 03:25:31 +09:00
const logger = new Logger('download');
logger.info(`Downloading ${chalk.cyan(url)} ...`);
const controller = new AbortController();
setTimeout(() => {
controller.abort();
}, 11 * 1000);
const response = await fetch(new URL(url).href, {
headers: {
'User-Agent': config.userAgent
},
timeout: 10 * 1000,
signal: controller.signal,
agent: u => u.protocol == 'http:' ? httpAgent : httpsAgent,
});
if (!response.ok) {
logger.error(`Got ${response.status} (${url})`);
throw response.status;
}
await pipeline(response.body, fs.createWriteStream(path));
logger.succ(`Download finished: ${chalk.cyan(url)}`);
}