From 889f069012cc0109b3e87d2952a58efafc44b308 Mon Sep 17 00:00:00 2001 From: srgooglo Date: Sun, 16 Oct 2022 17:58:33 +0200 Subject: [PATCH] added `download-file` util --- .../server/src/utils/download-file/index.js | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 packages/server/src/utils/download-file/index.js diff --git a/packages/server/src/utils/download-file/index.js b/packages/server/src/utils/download-file/index.js new file mode 100644 index 00000000..32df1d5f --- /dev/null +++ b/packages/server/src/utils/download-file/index.js @@ -0,0 +1,33 @@ +import fs from "fs" +import path from "path" +import axios from "axios" + +export default async (payload) => { + let { url, destination } = payload + + // if destination path is not provided, use cache folder + if (!destination) { + destination = path.resolve(global.uploadCachePath, path.basename(url)) + } + + console.log(destination) + + const writer = fs.createWriteStream(destination) + + const response = await axios({ + url, + method: "GET", + responseType: "stream" + }) + + response.data.pipe(writer) + + return new Promise((resolve, reject) => { + writer.on("finish", () => resolve({ + destination, + delete: () => fs.unlinkSync(destination), + read: () => fs.readFileSync(destination), + })) + writer.on("error", reject) + }) +} \ No newline at end of file