import * as fs from 'fs'; import * as https from 'https' import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; export const handler = async(event) => { const url = event.queryStringParameters.url; try { const fileName = await transferFileFromUrlToS3(url, 'demo-lambda-codewhisperer'); console.info(`Done.`); // get size of a file const stats = fs.statSync('/tmp/' + fileName); return { statusCode: 200, body: JSON.stringify(stats), }; } catch (error) { console.log(JSON.stringify(error)); return { statusCode: 500, body: JSON.stringify(error), }; } }; // Function for downloading a file from url parameter returning a promise async function downloadFileFromUrl(url) { return new Promise((resolve, reject) => { https.get(url, (response) => { // get the name of the file from a url const fileName = url.substring(url.lastIndexOf('/') + 1); const file = fs.createWriteStream('/tmp/' + fileName); console.log(`Downloading ${url} to /tmp/${fileName}.`); response.pipe(file); file.on('finish', () => { file.close(() => { resolve(fileName); }); }); }).on('error', (error) => { reject(error); }); }); } // function to upload a file to an s3 bucket piping the content async function uploadFileToS3(bucketName, fileName) { const fileContent = fs.readFileSync('/tmp/' + fileName); const s3Client = new S3Client({ region: 'us-east-1' }); const uploadResult = await s3Client.send(new PutObjectCommand({ Bucket: bucketName, Key: fileName, Body: fileContent, })); return uploadResult; } async function transferFileFromUrlToS3(url, bucketName) { console.info(`Transferring ${url} to ${bucketName}.`); // download the file from the url const fileName = await downloadFileFromUrl(url); // upload the file to s3 bucket const response = await uploadFileToS3(bucketName, fileName); return fileName; }