file-downloader.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import * as fs from 'fs';
  2. import * as path from 'path';
  3. import * as https from 'https';
  4. import * as http from 'http';
  5. export class FileDownloader {
  6. private tempDir: string;
  7. constructor() {
  8. // Use a temp directory that's accessible across different environments
  9. this.tempDir = path.join(process.cwd(), 'temp-downloads');
  10. this.ensureTempDirExists();
  11. }
  12. private ensureTempDirExists(): void {
  13. if (!fs.existsSync(this.tempDir)) {
  14. fs.mkdirSync(this.tempDir, { recursive: true });
  15. }
  16. }
  17. async downloadFile(url: string, filename: string): Promise<string> {
  18. return new Promise((resolve, reject) => {
  19. const filePath = path.join(this.tempDir, filename);
  20. // Clean up existing file if it exists
  21. if (fs.existsSync(filePath)) {
  22. fs.unlinkSync(filePath);
  23. }
  24. const file = fs.createWriteStream(filePath);
  25. const client = url.startsWith('https') ? https : http;
  26. const request = client.get(url, (response) => {
  27. if (response.statusCode === 200) {
  28. response.pipe(file);
  29. file.on('finish', () => {
  30. file.close();
  31. resolve(filePath);
  32. });
  33. } else {
  34. file.close();
  35. fs.unlink(filePath, () => {});
  36. reject(new Error(`Failed to download file: ${response.statusCode} ${response.statusMessage}`));
  37. }
  38. });
  39. request.on('error', (err) => {
  40. file.close();
  41. fs.unlink(filePath, () => {});
  42. reject(err);
  43. });
  44. });
  45. }
  46. async cleanupFile(filePath: string): Promise<void> {
  47. return new Promise((resolve, reject) => {
  48. if (fs.existsSync(filePath)) {
  49. fs.unlink(filePath, (err) => {
  50. if (err) {
  51. reject(err);
  52. } else {
  53. resolve();
  54. }
  55. });
  56. } else {
  57. resolve();
  58. }
  59. });
  60. }
  61. getTempDir(): string {
  62. return this.tempDir;
  63. }
  64. }