Build a Video Converter in Node.js & Express Using Handbrake.js Encoding Library in Browser Using Javascript Full Project For Beginners

 

 

 

npm init -y

 

 

npm i express ejs multer

 

 

npm i handbrake-js

 

 

npm i -g nodemon

 

 

index.js

 

 

const hbjs = require("handbrake-js");
const path = require("path");
const express = require("express");
const bodyparser = require("body-parser");
const multer = require("multer");
const fs = require("fs");

const app = express();

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/uploads");
  },
  filename: function (req, file, cb) {
    cb(
      null,
      file.fieldname + "-" + Date.now() + path.extname(file.originalname)
    );
  },
});

const videoFilter = function (req, file, callback) {
  var ext = path.extname(file.originalname);
  if (
    ext !== ".mp4" &&
    ext !== ".avi" &&
    ext !== ".flv" &&
    ext !== ".wmv" &&
    ext !== ".mov" &&
    ext !== ".mkv" &&
    ext !== ".gif" &&
    ext !== ".m4v"
  ) {
    return callback("This Extension is not supported");
  }
  callback(null, true);
};

var maxSize = 10000 * 1024 * 1024;

var uploadvideo = multer({
  storage: storage,
  limits: { fileSize: maxSize },
  fileFilter: videoFilter,
}).single("file");

app.use(express.static(path.resolve(__dirname + "public/uploads")));
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
app.set("view engine", "ejs");
app.get("/", (req, res) => {
  res.render("index");
});

app.post("/uploadvideo", (req, res) => {
  uploadvideo(req, res, function (err) {
    if (err) {
      return res.end("Error uploading file." + err);
    }
    res.json({
      path: req.file.path,
    });
  });
});

app.post("/convertvideo", (req, res) => {
  console.log(req.body);

  output = Date.now() + "output." + req.body.format;

  const options = {
    input: path.resolve(__dirname, req.body.path),
    output: output,
    preset: "Very Fast 480p30",
  };

  hbjs.exec(options, function (err, stdout, stderr) {
    if (err) throw err;
    console.log(stdout);

    res.json({
      path: output,
    });
  });
});

app.get("/download", (req, res) => {
  var pathoutput = req.query.path;
  console.log(pathoutput);
  var fullpath = path.join(__dirname, pathoutput);
  res.download(fullpath, (err) => {
    if (err) {
      fs.unlinkSync(fullpath);
      res.send(err);
    }
    fs.unlinkSync(fullpath);
  });
});

app.listen(3000, () => {
  console.log("App is listening on port 3000");
});

 

 

Now make a public/uploads directory to upload videos inside it

 

 

Now make a views directory and make an index.ejs file and copy paste the below code

 

 

views/index.ejs

 

 

<!DOCTYPE html>
<html>
  <head>
    <title>Video Converter in Node.js Using Handbrake.js</title>
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    />
  </head>
  <body>
    <div class="container">
      <br />
      <h1 class="text-center">Video Converter in Javascript</h1>
      <br />
      <form id="form" enctype="multipart/form-data">
        <div class="form-group">
          <label for="video">Select Video:</label>
          <input
            type="file"
            id="upload-input"
            accept="video/*"
            name="file"
            class="form-control"
            required
          />
        </div>
        <div class="progress">
          <div class="progress-bar" role="progressbar"></div>
        </div>
        <div class="form-group">
          <label for="format">Select Format:</label>
          <select class="form-control" id="format">
            <option value="mp4" selected>MP4</option>
            <option value="avi">AVI</option>
            <option value="wmv">WMV</option>
            <option value="mkv">MKV</option>
            <option value="flv">FLV</option>
            <option value="gif">GIF</option>
            <option value="mov">MOV</option>
            <option value="m4v">M4V</option>
          </select>
        </div>
        <div class="form-group">
          <button id="button" class="btn btn-danger btn-block">Download Video</button>
        </div>
      </form>
    </div>
  </body>
  <script src="https://cdn.jsdelivr.net/npm/browser-image-converter@0.1.1/dist/index.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script>
    var files;
    $("#form").on("submit", function (e) {
      e.preventDefault();
      //$('#upload-input').click();
      $(".progress-bar").text("0%");
      $("#button").text("Uploading File");
      $("#button").prop("disabled", "true");
      $(".progress-bar").width("0%");
      convertFile();
    });
    $("#upload-input").on("change", function () {
      files = $(this).get(0).files;
      var fileExtension = [
        "mp4",
        "avi",
        "gif",
        "flv",
        "m4v",
        "mkv",
        "mov",
        "wmv",
      ];
      if (
        $.inArray(
          $(this).val().split(".").pop().toLowerCase(),
          fileExtension
        ) == -1
      ) {
        $(this).val("");

        alert("Please upload a video file");
      }
    });
    function convertFile() {
      if (files.length > 0) {
        // create a FormData object which will be sent as the data payload in the
        // AJAX request
        var formData = new FormData();
        // loop through all the selected files and add them to the formData object
        for (var i = 0; i < files.length; i++) {
          var file = files[i];
          // add the files to formData object for the data payload
          formData.append("file", file, file.name);
        }
        console.log(formData);
        var formdata2 = new FormData();
        $.ajax({
          url: "/uploadvideo",
          type: "POST",
          data: formData,
          processData: false,
          contentType: false,
          success: function (data) {
            console.log(data);
            var data2 = { path: data.path,format:$('#format').val() };
            console.log("upload successful!\n" + data.path);
            $("#button").text("File Uploaded Now Processing");
            $("#button").prop("disabled", true);
            formdata2.append("path", data.path);
            $.ajax({
              url: "/convertvideo",
              type: "POST",
              data: JSON.stringify(data2),
              contentType: "application/json",
              dataType: "json",
              success: function (data) {
                window.open("/download?path=" + data.path);
                $("#button").text("Upload File");
                $("#button").prop("disabled", false);
                location.reload();
              },
            });
          },
          xhr: function () {
            // create an XMLHttpRequest
            var xhr = new XMLHttpRequest();
            // listen to the 'progress' event
            xhr.upload.addEventListener(
              "progress",
              function (evt) {
                if (evt.lengthComputable) {
                  // calculate the percentage of upload completed
                  var percentComplete = evt.loaded / evt.total;
                  percentComplete = parseInt(percentComplete * 100);
                  // update the Bootstrap progress bar with the new percentage
                  $(".progress-bar").text(percentComplete + "%");
                  $(".progress-bar").width(percentComplete + "%");
                  // once the upload reaches 100%, set the progress bar text to done
                  if (percentComplete === 100) {
                    $(".progress-bar").html("Done");
                  }
                }
              },
              false
            );
            return xhr;
          },
        });
      }
    }
  </script>
</html>

 

 

 

nodemon index.js

 

 

 

 

DOWNLOAD FULL SOURCE CODE

 

 

Leave a Reply