Skip to content

Instantly share code, notes, and snippets.

@skinnyfads
Last active March 6, 2023 19:34
Show Gist options
  • Save skinnyfads/92804767910463b575ecc24eb37c2c93 to your computer and use it in GitHub Desktop.
Save skinnyfads/92804767910463b575ecc24eb37c2c93 to your computer and use it in GitHub Desktop.
Download any files from direct link using Node.js
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