Last active
March 6, 2023 19:34
-
-
Save skinnyfads/92804767910463b575ecc24eb37c2c93 to your computer and use it in GitHub Desktop.
Download any files from direct link using Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from "node:fs"; | |
import https from "node:https"; | |
import http from "node:http"; | |
function getFileName(url: string) { | |
return new URL(url).pathname.split("/").pop(); | |
} | |
async function downloadFile(url: string): Promise<string> { | |
const urlProtocol = new URL(url).protocol; | |
const request = urlProtocol === "https:" ? https : http; | |
const fileName = getFileName(url); | |
const dir = "tmp"; | |
const filePath = `${process.cwd()}/${dir}/${fileName}`; | |
if (!fs.existsSync(dir)) fs.mkdirSync(dir); | |
const file = fs.createWriteStream(filePath); | |
return new Promise((resolve) => { | |
request.get(url, (res) => { | |
res.pipe(file); | |
file.on("finish", () => { | |
file.close(); | |
resolve(filePath); | |
}); | |
}); | |
}); | |
} | |
export default downloadFile; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment