From 9832eeab222a9912a0a54e42fb224448a65aa5a8 Mon Sep 17 00:00:00 2001 From: cupcakearmy Date: Fri, 21 Jun 2019 12:27:52 +0200 Subject: [PATCH] helper for downloading files to disk --- src/utils.ts | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/utils.ts b/src/utils.ts index 13e1b53..0e8f4b1 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,5 +1,7 @@ +import axios from 'axios' import { spawnSync, SpawnSyncOptions } from 'child_process' import { randomBytes } from 'crypto' +import { createWriteStream } from 'fs' export const exec = (command: string, args: string[], { env, ...rest }: SpawnSyncOptions = {}) => { @@ -42,4 +44,20 @@ export const singleToArray = (singleOrArray: T | T[]): T[] => Array.isArray(s export const filterObject = (obj: { [key: string]: T }, filter: (item: [string, T]) => boolean): { [key: string]: T } => Object.fromEntries(Object.entries(obj).filter(filter)) -export const filterObjectByKey = (obj: { [key: string]: T }, keys: string[]) => filterObject(obj, ([key]) => keys.includes(key)) \ No newline at end of file +export const filterObjectByKey = (obj: { [key: string]: T }, keys: string[]) => filterObject(obj, ([key]) => keys.includes(key)) + +export const downloadFile = async (url: string, to: string) => new Promise(async res => { + const { data: file } = await axios({ + method: 'get', + url: url, + responseType: 'stream', + }) + + const stream = createWriteStream(to) + + const writer = file.pipe(stream) + writer.on('close', () => { + stream.close() + res() + }) +}) \ No newline at end of file