Skip to content

Instantly share code, notes, and snippets.

@Hipnosis183
Last active November 21, 2024 22:50
Show Gist options
  • Save Hipnosis183/a9bd72e887468abb89b1c577fb980413 to your computer and use it in GitHub Desktop.
Save Hipnosis183/a9bd72e887468abb89b1c577fb980413 to your computer and use it in GitHub Desktop.
CORS Downloader
// Requires NPM package 'node-fetch'.
// npm install node-fetch@2
const fetch = require('node-fetch');
const fs = require('fs');
const http = require('http');
const util = require('util');
const pipeline = util.promisify(require('stream').pipeline);
http.createServer().listen(3000, '127.0.0.1', async () => {
console.log(`[CORS Downloader]\n`);
if (process.argv[2]) { await fileDownload(process.argv[2]); }
console.log(`\n[DONE]`);
process.exit(0); // Terminate server process.
});
const createPath = (output) => {
// Create output path if it doesn't exist.
const outputPath = `./${output}/`;
if (!fs.existsSync(outputPath)) { fs.mkdirSync(outputPath, { recursive: true }); }
return outputPath;
}
const fileDownload = async (url) => {
try { // Get file information from url.
const fileHost = new URL(url).hostname;
const fileName = url.split('/').pop();
const filePath = createPath(fileHost);
console.log(`[FILE] ${fileName}`);
try { // Download data from url.
const fileData = await fetch(url, { method: 'GET', headers: { 'Host': fileHost, 'Referer': fileHost } });
// Write downloaded data into a new file stream.
await pipeline(fileData.body, fs.createWriteStream(filePath + fileName));
console.log(`[OK] >>${filePath.slice(1)}${fileName}`);
} catch { // Failed to download file.
console.log(`[ERROR] ${filePath.slice(1)}${fileName} (${url})`);
} // Failed to parse url.
} catch { console.log(`[ERROR] ${url}`); }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment