Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import * as fs from 'fs';
- import * as https from 'https'
- import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
- export const handler = async(event) => {
- // get url from querystring in the event
- const url = event.queryStringParameters.url;
- // extract file name from url
- const fileName = url.substring(url.lastIndexOf('/') + 1);
- await transferFile(url, '/tmp/' + fileName);
- return {
- statusCode: 200,
- body: JSON.stringify('ok'),
- };
- };
- function uploadFileToS3(filePath, bucketName) {
- const s3Client = new S3Client({ region: 'us-east-1' });
- const command = new PutObjectCommand({
- Bucket: bucketName,
- Key: filePath,
- Body: fs.readFileSync(filePath),
- });
- return s3Client.send(command);
- }
- // function for downloading a file from an url to disk and resolve on closes
- function downloadFile(url, file) {
- return new Promise((resolve, reject) => {
- const fileStream = fs.createWriteStream(file);
- https.get(url, (response) => {
- response.pipe(fileStream);
- fileStream.on('close', () => {
- resolve();
- });
- }).on('error', (err) => {
- reject(err);
- });
- });
- }
- // async function for transferring a file from an url to a bucket
- async function transferFile(url, filePath) {
- await downloadFile(url, filePath);
- await uploadFileToS3(filePath, 'demo-lambda-codewhisperer');
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement