Feat: add download file try catch

This commit is contained in:
unitwk 2022-10-29 16:22:08 +08:00
parent 9a0a7b0d66
commit 1119e6e1f9

View File

@ -9,20 +9,21 @@ import logger from "./log";
export function downloadFileToLocalFile(url: string, localFilePath: string): Promise<boolean> { export function downloadFileToLocalFile(url: string, localFilePath: string): Promise<boolean> {
logger.info(`Download File: ${url} --> ${path.normalize(localFilePath)}`); logger.info(`Download File: ${url} --> ${path.normalize(localFilePath)}`);
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
const writeStream = fs.createWriteStream(path.normalize(localFilePath)); try {
const response = await axios<Readable>({ const writeStream = fs.createWriteStream(path.normalize(localFilePath));
url, const response = await axios<Readable>({
responseType: "stream" url,
}); responseType: "stream"
if (response.status > 299 || response.status < 200) { });
reject(new Error(`Download File: Target File response code is ${response.status} NOT 2XX.`)); pipeline(response.data, writeStream, (err) => {
if (err) {
reject(err);
} else {
resolve(true);
}
});
} catch (error) {
reject(error);
} }
pipeline(response.data, writeStream, (err) => {
if (err) {
reject(err);
} else {
resolve(true);
}
});
}); });
} }