Skip to content

Commit 448747f

Browse files
author
Sergey Koryshev
committed
refactored logic around downloading file
1 parent df1397a commit 448747f

File tree

1 file changed

+42
-39
lines changed

1 file changed

+42
-39
lines changed

tool.ts

Lines changed: 42 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -249,46 +249,49 @@ export async function downloadTool(
249249
}
250250

251251
tl.debug('creating stream');
252-
let file: NodeJS.WritableStream = fs.createWriteStream(destPath);
253-
file.on('open', async (fd) => {
254-
try {
255-
let stream = response.message.pipe(file);
256-
stream.on('close', () => {
257-
tl.debug('download complete');
258-
let fileSizeInBytes: number;
259-
try {
260-
fileSizeInBytes = _getFileSizeOnDisk(destPath);
261-
}
262-
catch (err) {
263-
fileSizeInBytes = NaN;
264-
tl.warning(`Unable to check file size of ${destPath} due to error: ${err.Message}`);
265-
}
266-
267-
if (!isNaN(fileSizeInBytes)) {
268-
tl.debug(`Downloaded file size: ${fileSizeInBytes} bytes`);
269-
} else {
270-
tl.debug(`File size on disk was not found`);
271-
}
272-
273-
if (!isNaN(downloadedContentLength) &&
274-
!isNaN(fileSizeInBytes) &&
275-
fileSizeInBytes !== downloadedContentLength) {
276-
tl.warning(`Content-Length (${downloadedContentLength} bytes) did not match downloaded file size (${fileSizeInBytes} bytes).`);
277-
}
278-
279-
resolve(destPath);
280-
});
281-
}
282-
catch (err) {
252+
const file: NodeJS.WritableStream = fs.createWriteStream(destPath);
253+
file
254+
.on('open', async (fd) => {
255+
try {
256+
response.message
257+
.on('error', (err) => {
258+
file.end();
259+
reject(err);
260+
})
261+
.pipe(file);
262+
} catch (err) {
263+
reject(err);
264+
}
265+
})
266+
.on('close', () => {
267+
tl.debug('download complete');
268+
let fileSizeInBytes: number;
269+
try {
270+
fileSizeInBytes = _getFileSizeOnDisk(destPath);
271+
} catch (err) {
272+
fileSizeInBytes = NaN;
273+
tl.warning(`Unable to check file size of ${destPath} due to error: ${err.Message}`);
274+
}
275+
276+
if (!isNaN(fileSizeInBytes)) {
277+
tl.debug(`Downloaded file size: ${fileSizeInBytes} bytes`);
278+
} else {
279+
tl.debug(`File size on disk was not found`);
280+
}
281+
282+
if (!isNaN(downloadedContentLength) &&
283+
!isNaN(fileSizeInBytes) &&
284+
fileSizeInBytes !== downloadedContentLength) {
285+
tl.warning(`Content-Length (${downloadedContentLength} bytes) did not match downloaded file size (${fileSizeInBytes} bytes).`);
286+
}
287+
288+
resolve(destPath);
289+
})
290+
.on('error', (err) => {
291+
file.end();
283292
reject(err);
284-
}
285-
});
286-
file.on('error', (err) => {
287-
file.end();
288-
reject(err);
289-
});
290-
}
291-
catch (error) {
293+
});
294+
} catch (error) {
292295
reject(error);
293296
}
294297
});

0 commit comments

Comments
 (0)