Node.js Express FFMPEG Merge Multiple Videos Web App

This article is a very important article. I mean in this Node.js Express FFMPEG Merge Multiple Videos Web App we are going to know very clearly about this. We hope you like this article. Please comment if you liked this article.

Node.js Express FFMPEG Merge Multiple Videos Web App

Node.js Express FFMPEG Merge Multiple Videos Web App

const express = require('express')

const app = express()

var dir="public";
var subDirectory = 'public/uploads'

if (!fs.existsSync(dir)){
    fs.mkdirSync(dir);

    fs.mkdirSync(subDirectory)

}


const PORT = process.env.PORT || 3000

app.get('/',(req,res) => {

    res.sendFile(__dirname + "/index.html")

})

app.listen(PORT,() => {
    console.log(`App is listening on Port ${PORT}`)
})
<!DOCTYPE html>
<html>
  <head>
    <title>Currency Converter in Javascript</title>
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    />
  </head>
  <body>
      <div class="container">
          <br><br>
          <h1 class="text-center">
              Merge Videos
          </h1>
          <br>
          <form action="/merge" method="post" enctype="multipart/form-data">
            <div class="form-group">
                <input type="file" name="files" multiple class="form-control" required>
            </div>
            <div class="form-group">
                <button class="btn btn-danger btn-block">
                    Merge Videos
                </button>
            </div>
        </form>
      </div>
</body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</html>
const multer = require('multer')


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, cb) {
    // Accept videos only
    if (!file.originalname.match(/.(mp4)$/)) {
        req.fileValidationError="Only video files are allowed!";
        return cb(new Error('Only video files are allowed!'), false);
    }
    cb(null, true);
};

var upload = multer({storage:storage,fileFilter:videoFilter})



app.use(express.static('public'))
const fs = require('fs')

const path = require('path')

const { exec } = require('child_process')

var list = ""

var listFilePath="public/uploads/" + Date.now() + 'list.txt'

var outputFilePath = Date.now() + 'output.mp4'




app.post('/merge',upload.array('files',1000),(req,res) => {
    if(req.files){
        
        req.files.forEach(file => {

            list += `file ${file.filename}`
            list += "n"
            
        });

        var writeStream = fs.createWriteStream(listFilePath)

        writeStream.write(list)

        writeStream.end()

        exec(`ffmpeg -safe 0 -f concat -i ${listFilePath} -c copy ${outputFilePath}`, (error, stdout, stderr) => {
          
            if (error) {
                console.log(`error: ${error.message}`);
                return;
            }
            else{
                console.log("videos are successfully merged")
            res.download(outputFilePath,(err) => {
                if(err) throw err

                req.files.forEach(file => {
                    fs.unlinkSync(file.path)                    
                });

                fs.unlinkSync(listFilePath)
                fs.unlinkSync(outputFilePath)

              

            })
        }
            
        })
    }
})
const express = require('express')

const fs = require('fs')

const path = require('path')

const { exec } = require('child_process')

var list = ""

var listFilePath="public/uploads/" + Date.now() + 'list.txt'

var outputFilePath = Date.now() + 'output.mp4'

const bodyParser = require('body-parser')

const multer = require('multer')

const app = express()

var dir="public";
var subDirectory = 'public/uploads'

if (!fs.existsSync(dir)){
    fs.mkdirSync(dir);

    fs.mkdirSync(subDirectory)

}

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, cb) {
    // Accept videos only
    if (!file.originalname.match(/.(mp4)$/)) {
        req.fileValidationError="Only video files are allowed!";
        return cb(new Error('Only video files are allowed!'), false);
    }
    cb(null, true);
};

var upload = multer({storage:storage,fileFilter:videoFilter})

app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
app.use(express.static('public'))


const PORT = process.env.PORT || 3000

app.get('/',(req,res) => {

    res.sendFile(__dirname + "/index.html")

})

app.post('/merge',upload.array('files',1000),(req,res) => {

    list = ""
    if(req.files){
        
        req.files.forEach(file => {

            list += `file ${file.filename}`
            list += "n"
            
        });

        var writeStream = fs.createWriteStream(listFilePath)

        writeStream.write(list)

        writeStream.end()

        exec(`ffmpeg -safe 0 -f concat -i ${listFilePath} -c copy ${outputFilePath}`, (error, stdout, stderr) => {
          
            if (error) {
                console.log(`error: ${error.message}`);
                return;
            }
            else{
                console.log("videos are successfully merged")
            res.download(outputFilePath,(err) => {
                if(err) throw err

                req.files.forEach(file => {
                    fs.unlinkSync(file.path)                    
                });

                fs.unlinkSync(listFilePath)
                fs.unlinkSync(outputFilePath)

              

            })
        }
            
        })
    }
})

app.listen(PORT,() => {
    console.log(`App is listening on Port ${PORT}`)
})

Read Also: Node.js Express FFMPEG Mp3 Pitch and Tempo Changer Web App

Final Words

Node.js Express FFMPEG Merge Multiple Videos Web App We have clearly identified the information you need through the article. If in doubt please let us know your doubts via the comment box Thank you.

Hi, I'm Selva a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Deekshi. Here, I post about programming to help developers.

Share on:

Leave a Comment