Search code examples
node.jsamazon-s3ffmpegfluent-ffmpeg

Upload ffmpeg file output to AWS s3 using NodeJS


The ffmpeg.output("path/file.mp4") need a string path as an argument to write the output file to it. But s3 bucket.upload(parms, ...) need a Binary File as a value to the Body: in parms JSON

Problem: Unable to provide file data using the file path to s3 bucket in NodeJS Environment

FFmpeg()
  .input("source.mp4") //video
  .setStartTime(startTime)
  .setDuration(duration)
  .output(output)    //output file path: string
  .on("end", function() {
    console.log("Processing finished successfully");
    var params = {
      Bucket: process.env.S3_BUCKET,
      Key: "videos/filename.mp4",
      Body: output    //binary file data to be provided not file path
    };
    const bucket = new S3({
      accessKeyId: process.env.S3_ACCESS_KEY_ID,
      secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
      region: process.env.S3_REGION
    });
    bucket.upload(params, function(err, data) {
      console.log(err, data);
    });
  })
  .run();

Solution

  • Done using fs.readFileSync() that provided me the file buffer which I passed to putObject()

    import fs = require("fs");
    
    const inputPath = "source.mp4"
    const outputPath = "clip.mp4";
    
    FFmpeg()
      .input(inputPath)            //input video path or URL
      .setStartTime(2)
      .setDuration(2)
      .output(outputPath)          //output file path: string
      .on("end", function() {
        console.log("Processing finished successfully");
        const fileContent = fs.readFileSync(outputPath);
        var params = {
          Bucket: process.env.S3_BUCKET,
          Key: "videos/clip.mp4",
          Body: fileContent        //got buffer by reading file path
        };
        const bucket = new S3({
          accessKeyId: process.env.S3_ACCESS_KEY_ID,
          secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
          region: process.env.S3_REGION
        });
        bucket.putObject(params, function(err, data) {
          console.log(err, data);
        });
      })
      .run();