From 5f59b980a753f1bd0418747cb76263dddd5dbb20 Mon Sep 17 00:00:00 2001 From: MeiMei <30769358+mei23@users.noreply.github.com> Date: Tue, 6 Nov 2018 07:53:03 +0900 Subject: [PATCH] Fix: download file (#3138) * Fix: url download * not explicitly close on end * resolve on stream finish * remove unnecessary code * reject on file error --- src/services/drive/upload-from-url.ts | 34 ++++++++++++++++++++------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/src/services/drive/upload-from-url.ts b/src/services/drive/upload-from-url.ts index 7d4785be0..96e258c98 100644 --- a/src/services/drive/upload-from-url.ts +++ b/src/services/drive/upload-from-url.ts @@ -35,21 +35,39 @@ export default async (url: string, user: IUser, folderId: mongodb.ObjectID = nul // write content at URL to temp file await new Promise((res, rej) => { const writable = fs.createWriteStream(path); + + writable.on('finish', () => { + res(); + }); + + writable.on('error', error => { + rej(error); + }); + const requestUrl = URL.parse(url).pathname.match(/[^\u0021-\u00ff]/) ? encodeURI(url) : url; - request({ + + const req = request({ url: requestUrl, proxy: config.proxy, + timeout: 10 * 1000, headers: { 'User-Agent': config.user_agent } - }) - .on('error', rej) - .on('end', () => { + }); + + req.pipe(writable); + + req.on('response', response => { + if (response.statusCode !== 200) { writable.close(); - res(); - }) - .pipe(writable) - .on('error', rej); + rej(response.statusCode); + } + }); + + req.on('error', error => { + writable.close(); + rej(error); + }); }); const instance = await fetchMeta();