The code below is made to:
- CONVERT some videos and store them on the folder of converted.
- CONCATENATE the converted videos.
- CLEAR the converted folder.
BUT currently, when executing the code, it concatenates while converting, and eventually throw an error. I need to execute each function with priority in his respective order.
const glob = require('glob');
const exec = require('child_process').exec;
const { unlink } = require("fs").promises;
function start(index) {
const path = `./files/${index}`;
const ConvertedVideos=path+"/converted/*.mp4";
const videos = glob.sync(path+"/videos/*.mp4");
const outputnoaudio = path+"/outputnoaudio.mp4";
//THIS IS THE ORDER OF EXECUTION
await convertVideos()
await withFfmpegConcatVideo()
await clearConverted()
//HERE THE DEFINITION OF EACH FUNCTION
async function convertVideos() {
return new Promise((resolve) => {
console.log('>>>Starting conversion!!!');
const promises = videos.map(
(video, index) => {
var command = `ffmpeg -i ${video} -c:v libx264 -vf scale=1920:1080 -r 60 -c:a aac -ar 48000 -b:a 160k -strict experimental -f mp4 ./converted/${index}.mp4`;
return new Promise((resolve) => {
exec(command, (error, stdout, stderr) => {
if (error) {
console.warn(error);
}
resolve(stdout ? stdout : stderr);
console.log('Converted video', index);
});
});
}
)
Promise.all(promises);
resolve();
})
}
async function withFfmpegConcatVideo() {
return new Promise((resolve) => {
console.log('Starting concatenation...');
var converted = glob.sync(ConvertedVideos);
console.log('There is ', converted.length, 'converted videos');
if (converted.length > 0) {
(async () =>
await concat({
output: outputnoaudio,
videos: converted,
transition: {
name: 'fade',
duration: 200
}
}))()
}
resolve(console.log('Conversion finished'));
})
}
async function clearConverted() {
return new Promise((resolve) => {
const converted =
glob.sync(ConvertedVideos)
if (converted.length === 0)
return Promise.resolve([])
const promises =
converted.map(v => unlink(v).then(_ => {
v
}))
Promise.all(promises).then('Clean done.')
resolve();
})
}
}
start(1);
I want to keep clean and reusable code. May you help me?