Skip to content

Instantly share code, notes, and snippets.

@rin
Created December 23, 2020 19:30
Show Gist options
  • Save rin/dc745ab3ecd71e464245172d61160d8d to your computer and use it in GitHub Desktop.
Save rin/dc745ab3ecd71e464245172d61160d8d to your computer and use it in GitHub Desktop.
AWS Lambda to download youtube videos to S3
// To use this, put it in a folder, install ytdl-core with `npm i ytdl-core`, then create a ZIP with the content of the folder and deploy it.
// https://docs.aws.amazon.com/lambda/latest/dg/nodejs-package.html#nodejs-package-dependencies
var AWS = require('aws-sdk');
const ytdl = require('ytdl-core');
const stream = require('stream');
var s3 = new AWS.S3();
exports.handler = async (event, context, cb) => {
const { videoUrl, key, bucket } = event;
const bucketName = bucket || process.env.BUCKET;
const keyName = `${key}-${context.awsRequestId}.mp4`;
const uploadStream = ({ Bucket, Key }) => {
const pass = new stream.PassThrough();
return {
writeStream: pass,
promise: s3.upload({Bucket, Key, Body: pass}).promise(),
};
}
const { writeStream, promise } = uploadStream({Bucket: bucketName , Key: keyName});
const pipeline = ytdl(videoUrl).pipe(writeStream);
return promise
.then(() => `Upload completed successfully. Find it at ${bucketName}/${keyName}`))
.catch((err) => {
return ('Upload failed.', err.message);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment