| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- import * as fs from 'fs';
- import * as path from 'path';
- import * as https from 'https';
- import * as http from 'http';
- export class FileDownloader {
- private tempDir: string;
- constructor() {
- // Use a temp directory that's accessible across different environments
- this.tempDir = path.join(process.cwd(), 'temp-downloads');
- this.ensureTempDirExists();
- }
- private ensureTempDirExists(): void {
- if (!fs.existsSync(this.tempDir)) {
- fs.mkdirSync(this.tempDir, { recursive: true });
- }
- }
- async downloadFile(url: string, filename: string): Promise<string> {
- return new Promise((resolve, reject) => {
- const filePath = path.join(this.tempDir, filename);
-
- // Clean up existing file if it exists
- if (fs.existsSync(filePath)) {
- fs.unlinkSync(filePath);
- }
- const file = fs.createWriteStream(filePath);
- const client = url.startsWith('https') ? https : http;
- const request = client.get(url, (response) => {
- if (response.statusCode === 200) {
- response.pipe(file);
- file.on('finish', () => {
- file.close();
- resolve(filePath);
- });
- } else {
- file.close();
- fs.unlink(filePath, () => {});
- reject(new Error(`Failed to download file: ${response.statusCode} ${response.statusMessage}`));
- }
- });
- request.on('error', (err) => {
- file.close();
- fs.unlink(filePath, () => {});
- reject(err);
- });
- });
- }
- async cleanupFile(filePath: string): Promise<void> {
- return new Promise((resolve, reject) => {
- if (fs.existsSync(filePath)) {
- fs.unlink(filePath, (err) => {
- if (err) {
- reject(err);
- } else {
- resolve();
- }
- });
- } else {
- resolve();
- }
- });
- }
- getTempDir(): string {
- return this.tempDir;
- }
- }
|