How to upload and save streams from a client to Node Server in an mp4

I am trying to find a way to save video from a client camera (navigator.getUserMedia) Stream as .mp4 onto a Node.Js server, but I can’t seem to find a way to put it all together.

How can I upload the video stream chunks from the camera to the server and save it in an .mp4 file.

Thank you all in advance.

LOCAL ON THE BROWSER :

let myStreamHandler = function (myStream) {
    // Send myStream to server
};

let myErrorHandler = function (error) {
    alert(error);
};

if (typeof navigator.mediaDevices.getUserMedia === "undefined") {
    navigator.getUserMedia({ video: true, audio: true }, myStreamHandler, myErrorHandler);
} else {
    navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(myStreamHandler).catch(myErrorHandler);
}

ON REMOTE NODE SERVER :

var http = require('http');
var router = require('routes')();
var Busboy = require('busboy');
var port = 5000;

// Define our route for uploading files
router.addRoute('/video_stream', function (req, res, params) {
  if (req.method === 'POST') {

    // Create an Busyboy instance passing the HTTP Request headers.
    var busboy = new Busboy({ headers: req.headers });

    // Listen for event when Busboy finds a file to stream.
    busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {

      // We are streaming! Handle chunks
      file.on('data', function (data) {
        // Here we can act on the data chunks streamed and save them as mp4.
    });

      // Completed streaming the file.
      file.on('end', function () {
        console.log('Finished with ' + fieldname);
    });
  });

    // Listen for event when Busboy finds a non-file field.
    busboy.on('field', function (fieldname, val) {
      // Do something with non-file field.
  });

    // Listen for event when Busboy is finished parsing the form.
    busboy.on('finish', function () {
      res.statusCode = 200;
      res.end();
  });

    // Pipe the HTTP Request into Busboy.
    req.pipe(busboy);
}
});

var server = http.createServer(function (req, res) {

  // Check if the HTTP Request URL matches on of our routes.
  var match = router.match(req.url);

  // We have a match!
  if (match) match.fn(req, res, match.params);
});

server.listen(port, function () {
  console.log('Listening on port ' + port);
});

20 thoughts on “How to upload and save streams from a client to Node Server in an mp4”

Leave a Comment