SudoDotDog / IO
1
/**
2
 * @author WMXPY
3
 * @namespace External
4
 * @description External
5
 */
6

7 3
import * as Fs from "fs";
8 3
import * as Http from "http";
9 3
import * as Https from "https";
10 3
import { removeFile } from "../file/file";
11

12 3
export const getHttpClient = (url: string): typeof Https | typeof Http => {
13

14 0
    if (url.substring(0, 5) === 'https') {
15 0
        return Https;
16
    }
17 0
    return Http;
18
};
19

20 3
export const getExternalData = (url: string): Promise<string> =>
21 0
    new Promise<string>((resolve: (data: string) => void, reject: (reason: Error) => void) => {
22

23 0
        const client: typeof Http | typeof Https = getHttpClient(url);
24 0
        const stringBuffer: string[] = [];
25

26 0
        client.get(url, (response: Http.IncomingMessage) => {
27 0
            response.on('data', (chunk: string) => {
28 0
                stringBuffer.push(chunk);
29
            });
30 0
            response.on('end', () => {
31 0
                resolve(stringBuffer.join(''));
32
            });
33 0
        }).on("error", (error: Error) => {
34 0
            reject(error);
35
        });
36
    });
37

38 3
export const downloadFile = (url: string, targetPath: string): Promise<void> =>
39 3
    new Promise<void>((resolve: () => void, reject: (reason: Error) => void) => {
40

41 3
        const client: typeof Http | typeof Https = getHttpClient(url);
42

43 3
        const writeStream: Fs.WriteStream = Fs.createWriteStream(targetPath);
44 3
        writeStream.on('finish', () => {
45 3
            resolve();
46 3
            writeStream.close();
47 3
            return;
48
        });
49 3
        writeStream.on('error', (error: Error) => {
50 0
            reject(error);
51 0
            writeStream.close();
52 0
            return;
53
        });
54

55 3
        const request: Http.ClientRequest = client.get(url, (response: Http.IncomingMessage) => {
56 0
            response.pipe(writeStream);
57 0
            return;
58
        });
59 3
        request.on('error', (error: Error) => {
60 0
            removeFile(targetPath).then(() => {
61 0
                reject(error);
62 0
            }).catch(() => {
63 0
                reject(error);
64
            });
65
        });
66
    });

Read our documentation on viewing source code .

Loading