To use AWS Lambda with FFMPEG Lambda layer in Node JS, you can follow the below steps:
First, create a lambda function in AWS console using Node JS runtime.
Next, add the FFMPEG Lambda layer to your function by selecting the layer ARN in the Function code → Layers section.
In your Node JS code, make sure to import the FFMPEG command by requiring it like this:
const ffmpeg = require('/opt/ffmpeg')
const fs = require('fs');
const exec = require('child_process').exec;
exports.handler = async (event) => {
return new Promise((resolve, reject) => {
const inputFile = '/tmp/input.mp4';
const outputFile = '/tmp/output.avi';
const s3 = new AWS.S3();
const getObjectParams = {
Bucket: 'my-bucket',
Key: 'my-video.mp4'
};
const file = fs.createWriteStream(inputFile);
s3.getObject(getObjectParams).createReadStream().pipe(file);
file.on('finish', () => {
const command = `${ffmpeg} -i ${inputFile} ${outputFile}`;
exec(command, (error, stdout, stderr) => {
if (error) {
reject(error);
} else {
const putObjectParams = {
Body: fs.readFileSync(outputFile),
Bucket: 'my-bucket',
Key: 'my-video.avi'
};
s3.putObject(putObjectParams, (error) => {
if (error) {
reject(error);
} else {
resolve('Conversion completed');
}
});
}
});
});
});
};
In the above code, we are first getting the video file from S3 bucket and creating a writable stream to write it to a temporary file. Then, we are using FFMPEG command to convert the video and writing the output to another temporary file. Finally, we are uploading the output file to S3 bucket.
Note that we are using 'fs' and 'child_process' modules to perform file operations and execute shell command respectively. Also, we are using AWS SDK for Node JS to interact with S3 bucket.
Once you have written the code, save and deploy it to your Lambda function. You can then test it by invoking the function manually or setting up an event trigger.
Asked: 2023-03-10 11:00:00 +0000
Seen: 10 times
Last updated: Aug 26 '21