const AWS = require('aws-sdk');
const fs = require('fs');
const path = require('path');
const { v4: uuidv4 } = require('uuid'); // For generating a unique temp file name
const concurrentDownloads = 5; // Adjust the number of concurrent downloads
const chunkSize = 10 * 1024 * 1024; // 10MB chunks
const maxRetries = 3; // Maximum number of retries for failed requests
// Initialize S3 client
const s3 = new AWS.S3({
region: 'your-bucket-region', // Update this
});
// Update these variables
const bucketName = 'your-bucket-name';
const objectKey = 'path/to/your/large/file.txt';
// Function to get object metadata (to determine the file size)
async function getObjectMetadata() {
const params = { Bucket: bucketName, Key: objectKey };
try {
const data = await s3.headObject(params).promise();
return data.ContentLength;
} catch (err) {
console.error('Error fetching object metadata:', err);
process.exit(1);
}
}
// Function to download a range of the file with retry logic
async function downloadFileRange(rangeStart, rangeEnd, writeStream, retryCount = 0) {
const params = {
Bucket: bucketName,
Key: objectKey,
Range: `bytes=${rangeStart}-${rangeEnd}`,
};
try {
const data = await s3.getObject(params).promise();
writeStream.write(data.Body);
} catch (err) {
console.error(`Error downloading range ${rangeStart}-${rangeEnd}:`, err);
if (retryCount < maxRetries) {
// Exponential backoff for retries
const delay = Math.pow(2, retryCount) * 1000; // 2^retryCount seconds
console.log(`Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
await downloadFileRange(rangeStart, rangeEnd, writeStream, retryCount + 1);
} else {
console.error('Maximum retries exceeded. Download failed.');
process.exit(1);
}
}
}
// Main execution
(async () => {
const fileSize = await getObjectMetadata();
const tempFileName = `temp-${uuidv4()}.download`;
const writeStream = fs.createWriteStream(tempFileName, { flags: 'w' });
// Calculate ranges for concurrent downloads
const ranges = [];
for (let i = 0; i < concurrentDownloads; i++) {
const start = i * chunkSize;
const end = Math.min(start + chunkSize - 1, fileSize - 1);
if (start < fileSize) {
ranges.push({ start, end });
}
}
// Download ranges concurrently with retry support
await Promise.all(ranges.map((range) => downloadFileRange(range.start, range.end, writeStream)));
writeStream.end();
console.log('Download completed. Renaming file...');
// Rename the file to the original name (assuming you want to keep the original name)
const originalFileName = path.basename(objectKey);
fs.renameSync(tempFileName, originalFileName);
console.log(`File saved as ${originalFileName}`);
})();