Skip to main content

How to run FFmpeg using NodeJS

· 2 min read

Setting up

This tutorial assumes you already have NodeJS installed

Use the following to set up a new folder and package.json file

mkdir ffmpeg-tutorial
cd ffmpeg ffmpeg-tutorial
npm init # enter ffmpeg-tutorial as the name and then skip through the rest

You should now have package.json which looks like the following:

{
"name": "ffmpeg-tutorial",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}

Next run the following to install FFmpeg:

npm i -s ffmpeg-static

And then create a new src folder with main.js inside.

mkdir src
touch src/main.js

Next make a data folder to store the input and output file:

mkdir data

Download the following sample file and put it into data folder. Rename it to input.mkv

https://samples.tdarr.io/api/v1/samples/sample__240__libx264__aac__30s__video.mkv

Code

Open up main.js and add the following:

const ffmpegPath = require('ffmpeg-static');
const childProcess = require('child_process');

const inputFile = `${process.cwd()}/data/input.mkv`;
const outputFile = `${process.cwd()}/data/output.mkv`;

// spawn an ffmpeg process
const child = childProcess.spawn(
ffmpegPath,
// note, args must be an array when using spawn
[
'-i',
`${inputFile}`,
// copy over the input streams of the input file to the output file
'-map',
'0',
'-c',
'copy',
// transcode the file into hevc from h264
'-c:v',
'libx265',
`${outputFile}`,
],
);

child.on('error', () => {
// catches execution error (bad file)
console.log(`Error executing binary: ${ffmpegPath}`);
});

child.stdout.on('data', (data) => {
console.log(data.toString());
});

child.stderr.on('data', (data) => {
console.log(data.toString());
});

child.on('close', (code) => {
console.log(`Process exited with code: ${code}`);
if (code === 0) {
console.log(`FFmpeg finished successfully`);
} else {
console.log(`FFmpeg encountered an error, check the console output`);
}
});

Run node ./src/main.js and FFmpeg should successfully transcode the file.

info

Get started using Tdarr transcode automation for free with this link:

https://tdarr.io/download/