nodemediajs
v3.1.5
Published
Powerful video processing package that allow you to handle videos easily with ffmpeg.
Maintainers
Readme
Multi-Media
A TypeScript/Node.js library for working with video files through FFmpeg and FFprobe.
nodemediajs provides a simple, strongly typed API for video metadata extraction, format conversion, audio extraction, trimming, and splitting, without requiring you to work directly with FFmpeg commands. Every processing method resolves with the path of the file(s) it created.
Features
- Video metadata extraction (codec, resolution, frame rate, bitrate, aspect ratio, duration)
- Audio metadata extraction
- Format (container) metadata extraction
- File metadata extraction (name, folder, extension, size, timestamps)
- Complete media metadata in a single call
- Video format conversion (10 formats)
- Video to audio conversion (6 formats)
- Video trimming (between two points, from a point, or until a point)
- Video splitting into two parts
- Every processing method returns the generated output path(s)
- Progress callbacks (with separate callbacks for each part when splitting)
- Standalone helper functions (no class instance needed)
- Custom error classes
- Full TypeScript type definitions
- ESM and CommonJS support
- No terminal output of its own: the library never prints to
stdout, so you decide how to show progress
Requirements
- FFmpeg (this package is a wrapper around it; without FFmpeg it can't do anything for you)
- FFprobe (ships together with FFmpeg)
- Node.js
>=18
FFmpeg and FFprobe must be installed and available in your system's PATH.
You can verify the installation with:
ffmpeg -version
ffprobe -versionInstallation
npm install nodemediajsBasic Usage
Video is the default export of the package (it is also available as a named export).
import Video from "nodemediajs";
// or: import { Video } from "nodemediajs";
const video = new Video("./input.mp4");
const outputPath = await video.toMime("webm", "./output");
console.log(outputPath); // ./output/video-1765000000000-aB3dE9xZ.webmCommonJS:
const { default: Video } = require("nodemediajs");
const video = new Video("./input.mp4");A Video instance stores the input path. Every method validates the file with FFprobe before doing any work, so passing a missing file or a non-video file throws an InvalidVideoError.
Standalone Functions
If you don't need an instance, the same operations are available as plain functions:
import {
isVideo,
videoToMime,
videoToAudio,
trimVideo,
splitVideo,
} from "nodemediajs";
const webmPath = await videoToMime("./input.mp4", "webm", "./output");
const clipPath = await trimVideo("./input.mp4", 10, 30, "./output", {
onProgress: (progress) => console.log(progress.progress),
});
const [part1, part2] = await splitVideo("./input.mp4", 30, "./output");See API Overview for the full list.
Metadata
All metadata methods are asynchronous and run FFprobe under the hood.
The input must be a video file. Images (PNG, JPEG, WebP, GIF, APNG) and audio-only files are rejected with
InvalidVideoError. See Known Limitations.
Video Metadata
const metadata = await video.videoMeta();
console.log(metadata);Returns:
| Field | Type | Description |
| --------------- | -------- | -------------------------------- |
| codecName | string | Codec short name |
| codecLongName | string | Codec full name |
| width | number | Frame width in pixels |
| height | number | Frame height in pixels |
| frameRate | string | Average frame rate as a ratio |
| bitrate | number | Video bitrate in bits per second |
| aspectRatio | string | Display aspect ratio |
| duration | number | Duration in seconds |
Audio Metadata
const audio = await video.audioMeta();
console.log(audio);Returns:
| Field | Type | Description |
| --------------- | -------- | ------------------------- |
| codecName | string | Codec short name |
| codecLongName | string | Codec full name |
| sampleRate | number | Sample rate in Hz |
| channels | number | Number of audio channels |
| bitrate | number | Audio bitrate |
| duration | number | Audio duration in seconds |
If the video has no audio stream, the strings are empty and the numbers are 0.
Format Metadata
const format = await video.formatMeta();
console.log(format);Returns:
| Field | Type | Description |
| ---------- | -------- | ------------------------------------------------------ |
| name | string | Container name (for example mov,mp4,m4a,3gp,3g2,mj2) |
| longName | string | Container full name |
| duration | number | Total duration in seconds |
| bitrate | number | Overall bitrate in bits per second |
File Metadata
const file = await video.fileMeta();
console.log(file);Returns:
| Field | Type | Description |
| ---------------- | -------- | ------------------------------------ |
| filename | string | File name with extension |
| path | string | Path as it was provided |
| folder | string | Containing folder |
| extension | string | Extension including the dot (.mp4) |
| size | number | File size in bytes |
| createdAt | Date | Creation time |
| updatedAt | Date | Last modification time |
| lastAccessTime | Date | Last access time |
Complete Metadata
const metadata = await video.meta();
console.log(metadata);Returns everything in one object:
{
video: VideoMetaData;
audio: AudioMetaData;
format: FormatMetaData;
file: FileMetaData;
tags: Record<string, string>; // container tags such as title or encoder
}You can also retrieve metadata without creating a Video instance:
const metadata = await Video.meta("./input.mp4");Video Conversion
Convert a video into another supported video format:
const outputPath = await video.toMime("webm", "./output");| Parameter | Type | Description |
| ------------- | ---------------- | ----------------------------------------------------- |
| type | VideoMimeTypes | Target format |
| destination | string | Output folder (must already exist) |
| options | VideoOption | Optional. Progress callback |
Returns: Promise<string>, the path of the converted file.
Supported video formats:
mp4, mkv, webm, avi, mov, mpeg, ogv, flv, m4v, 3gpThe library automatically configures the appropriate FFmpeg container and codecs for the selected format (see Supported Formats).
Things to know:
destinationis a folder, not a file name. It must exist, otherwise aPathNotExisterror is thrown. Create it first if needed:import { mkdir } from "node:fs/promises"; await mkdir("./output", { recursive: true });The output file is named
video-<timestamp>-<random>.<extension>(for examplevideo-1765000000000-aB3dE9xZ.webm). You cannot choose the name, so use the returned path (or rename the file yourself afterwards).The original file is never modified.
The video is re-encoded with FFmpeg's default quality settings, so large files can take a while.
If FFmpeg fails, an
FFmpegErroris thrown. A partial output file may be left in the destination folder.
Video to Audio
Extract the audio track from a video:
const audioPath = await video.toAudio("mp3", "./output");| Parameter | Type | Description |
| ------------- | ---------------- | ------------------------------------------------- |
| type | AudioMimeTypes | Target audio format |
| destination | string | Output folder (must already exist) |
| options | VideoOption | Optional. Progress callback |
Returns: Promise<string>, the path of the audio file.
Supported audio formats:
mp3, m4a, wav, flac, ogg, aiffThe output file is named audio-<timestamp>-<random>.<extension>. The video stream is dropped, and audio is encoded at 44.1 kHz stereo (and 192k bitrate for the lossy formats).
If the video has no audio stream, FFmpeg has nothing to extract and an
FFmpegErroris thrown. UseaudioMeta()first (codecName === ""means no audio) if you need to check.
Trimming
Trim a video between two points:
const clipPath = await video.trim(10, 30, "./output");This creates a new video containing the section between 10 and 30 seconds.
| Parameter | Type | Description |
| ------------- | ------------- | ------------------------------------------------------------- |
| start | number | Start point in seconds (>= 0) |
| end | number | End point in seconds (greater than start, not past the video) |
| destination | string | Output folder (must already exist) |
| options | VideoOption | Optional. Progress callback |
Returns: Promise<string>, the path of the trimmed file.
Trim From a Specific Point
const path = await video.trimStart(10, "./output");This keeps the video from 10 seconds until the end.
Trim Until a Specific Point
const path = await video.trimEnd(30, "./output");This keeps the video from the beginning until 30 seconds.
Things to know:
endmay equal the video duration, but a value greater than the duration throwsInvalidSecondLimit. This applies totrimandtrimEnd.- Trimming uses FFmpeg stream copy (
-c copy). It is very fast and does not re-encode, but cuts snap to keyframes, so they are not frame-accurate. See Known Limitations. - The output keeps the original file extension and is named
video-<timestamp>-<random><ext>. - Invalid ranges throw
InvalidSecondLimit(see Error Handling).
Splitting
Split a video at a specific point:
const [firstPart, secondPart] = await video.split(30, "./output");For example, a 60-second video split at 30 seconds produces two video files:
0s ───────── 30s ───────── 60s
part 1 part 2| Parameter | Type | Description |
| ------------- | ------------------ | ----------------------------------------------------------------- |
| second | number | Split point in seconds (> 0 and less than the video duration) |
| destination | string | Output folder (must already exist) |
| options | VideoSplitOption | Optional. onProgressV1 and onProgressV2 callbacks |
Returns: Promise<Array<string>>, the paths of the two parts: [firstPart, secondPart].
Things to know:
- The split point must be greater than
0and less than the video duration, otherwiseInvalidSecondLimitStartis thrown. - Both parts are created in parallel using stream copy, and keep the original extension.
- Each part reports progress to its own callback (see below), so the updates are never mixed together.
- Like trimming, split points snap to keyframes. See Known Limitations.
Progress Tracking
Processing methods accept a progress callback through the options parameter.
await video.toMime("webm", "./output", {
onProgress: (progress) => {
console.log(progress);
},
});The callback receives:
{
frame: number | undefined;
fps: number | undefined;
bitrate: string | undefined;
size: number;
time: number;
speed: string | undefined;
status: "continue" | "end";
duration: number;
progress: number;
}| Field | Description |
| ---------- | ------------------------------------------------------------------------ |
| frame | Frames processed so far |
| fps | Processing frame rate |
| bitrate | Current output bitrate reported by FFmpeg (for example 1200.5kbits/s) |
| size | Output size written so far, in bytes |
| time | Seconds of media processed so far |
| speed | Processing speed reported by FFmpeg (for example 2.4x) |
| status | continue while running, end when FFmpeg reports it is finished |
| duration | Total duration (seconds) of the media being produced (see below) |
| progress | A value between 0 and 1 |
For example:
await video.toAudio("mp3", "./output", {
onProgress: (progress) => {
console.log(`${(Number(progress.progress) * 100).toFixed(2)}%`);
},
});The callback parameter is typed as
Record<string, string | number | undefined>, so wrap numeric fields withNumber(...)in strict TypeScript.
What duration and progress are measured against
| Method | duration is... |
| ------------------------------------- | ----------------------------------------- |
| toMime, toAudio | The duration of the input video |
| trim, trimStart, trimEnd | The length of the clip being created |
| split | The length of each part (per callback) |
Because FFmpeg reports its own timestamps, progress can finish a little below 1 (for example 0.997). Use status === "end" to detect completion rather than waiting for progress === 1.
Progress while splitting
split runs two FFmpeg jobs at the same time, so it takes two callbacks:
const [part1, part2] = await video.split(30, "./output", {
onProgressV1: (p) => console.log("part 1:", p.progress),
onProgressV2: (p) => console.log("part 2:", p.progress),
});| Callback | Receives progress of |
| -------------- | ------------------------ |
| onProgressV1 | The first part (0 → split point) |
| onProgressV2 | The second part (split point → end) |
Options shape
type VideoOption = {
onProgress: (progressData: Record<string, string | number | undefined>) => void;
};
type VideoSplitOption = {
onProgressV1: (progressData: Record<string, string | number | undefined>) => void;
onProgressV2: (progressData: Record<string, string | number | undefined>) => void;
};When you pass an options object in TypeScript, provide all of its callbacks. You can also simply omit the options parameter, in which case no progress callbacks are used.
The library does not print anything on its own. If you want a terminal progress bar, build it inside your callback.
Error Handling
The package throws custom errors for common failures:
| Error | error.name | Thrown when |
| ------------------------- | ------------------- | --------------------------------------------------------------- |
| InvalidVideoError | InvalidVideoError | The input is not a file, or is not a video |
| FFprobeNotFound | CommandNotFound | FFprobe is not installed or not in PATH |
| FFmpegNotFound | CommandNotFound | FFmpeg is not installed or not in PATH |
| InvalidPath | InvalidPath | A path argument (destination) is not a string |
| PathNotExist | PathNotExist | The output folder does not exist |
| InvalidSecond | InvalidSecond | A seconds argument is not a number |
| InvalidSecondLimit | InvalidSecond | Trim range is empty, negative, or ends past the video duration |
| InvalidSecondLimitStart | InvalidSecond | Split point is <= 0 or not less than the video duration |
| FFmpegError | FFmpegError | FFmpeg exited with a non-zero code |
| InvalidMime | InvalidMime | An unsupported video or audio format was requested |
For example:
import Video from "nodemediajs";
try {
const video = new Video("./input.mp4");
const output = await video.toMime("webm", "./output");
console.log("Saved to", output);
} catch (error) {
if (error instanceof Error) {
switch (error.name) {
case "InvalidVideoError":
console.error("That file is not a video.");
break;
case "CommandNotFound":
console.error("Install FFmpeg and FFprobe first.");
break;
case "PathNotExist":
console.error("Create the output folder first.");
break;
case "FFmpegError":
console.error("FFmpeg failed:", error.message);
break;
default:
console.error(error.message);
}
}
}Match errors by
error.name. The error classes are not exported from the package entry point, soinstanceofchecks against them are not possible. Note thatFFprobeNotFoundandFFmpegNotFoundshare the nameCommandNotFound, and theInvalidSecond*errors share the nameInvalidSecond. When you need to tell them apart, checkerror.message.
Supported Formats
Video
| Format | Extension | Video codec | Audio codec |
| ------------ | --------- | ------------ | ----------- |
| MPEG-4 | .mp4 | libx264 | aac |
| Matroska | .mkv | libx264 | aac |
| WebM | .webm | libvpx-vp9 | libopus |
| AVI | .avi | mpeg4 | mp3 |
| QuickTime | .mov | libx264 | aac |
| MPEG | .mpeg | mpeg2video | mp2 |
| Ogg Video | .ogv | libtheora | libvorbis |
| Flash Video | .flv | flv | mp3 |
| MPEG-4 Video | .m4v | libx264 | aac |
| 3GPP | .3gp | h263 | aac |
Audio
| Format | Extension | Codec | Bitrate | Sample rate | Channels |
| ------------ | --------- | ------------ | -------- | ----------- | -------- |
| MP3 | .mp3 | libmp3lame | 192k | 44100 Hz | 2 |
| MPEG-4 Audio | .m4a | aac | 192k | 44100 Hz | 2 |
| WAV | .wav | pcm_s16le | lossless | 44100 Hz | 2 |
| FLAC | .flac | flac | lossless | 44100 Hz | 2 |
| Ogg Vorbis | .ogg | libvorbis | 192k | 44100 Hz | 2 |
| AIFF | .aiff | pcm_s16be | lossless | 44100 Hz | 2 |
API Overview
Video
new Video(input: string)| Method | Returns | Description |
| ------------------------------------------ | ------------------------- | ---------------------------------------- |
| videoMeta() | Promise<VideoMetaData> | Get video stream metadata |
| audioMeta() | Promise<AudioMetaData> | Get audio stream metadata |
| fileMeta() | Promise<FileMetaData> | Get file metadata |
| formatMeta() | Promise<FormatMetaData> | Get container/format metadata |
| meta() | Promise<MetaData> | Get complete metadata |
| isVideo() | Promise<boolean> | Check whether the input is a valid video |
| toMime(type, destination, options?) | Promise<string> | Convert to another video format |
| toAudio(type, destination, options?) | Promise<string> | Extract/convert audio |
| trim(start, end, destination, options?) | Promise<string> | Trim between two timestamps |
| trimStart(second, destination, options?) | Promise<string> | Trim from a timestamp to the end |
| trimEnd(second, destination, options?) | Promise<string> | Trim from the beginning to a timestamp |
| split(second, destination, options?) | Promise<Array<string>> | Split a video at a timestamp |
Static methods: Video.meta(path) and Video.isVideo(path).
Standalone Functions
| Function | Returns | Description |
| ----------------------------------------------------- | ------------------------ | ---------------------------------------- |
| isVideo(input) | Promise<boolean> | Check whether the input is a valid video |
| videoToMime(input, type, destination, options?) | Promise<string> | Convert to another video format |
| videoToAudio(input, type, destination, options?) | Promise<string> | Extract/convert audio |
| trimVideo(input, start, end, destination, options?) | Promise<string> | Trim between two timestamps |
| splitVideo(input, second, destination, options?) | Promise<Array<string>> | Split a video at a timestamp |
There is no standalone
meta()function. UseVideo.meta(path).
Types
The following types are exported for TypeScript users:
import type {
VideoMetaData,
AudioMetaData,
FormatMetaData,
FileMetaData,
MetaData,
VideoMimeTypes,
AudioMimeTypes,
VideoFormatConfig,
AudioFormatConfig,
} from "nodemediajs";The option types (VideoOption, VideoSplitOption) are not exported from the entry point. If you need them, derive them from the method signatures:
import type Video from "nodemediajs";
type VideoOption = NonNullable<Parameters<Video["toMime"]>[2]>;
type VideoSplitOption = NonNullable<Parameters<Video["split"]>[2]>;How It Works
The package uses:
- FFprobe for inspecting media files and extracting metadata.
- FFmpeg for video conversion, audio conversion, trimming, and splitting.
- Node.js child processes (
execFileandspawn, never a shell) to run them.
The library handles the FFmpeg command construction and exposes a higher-level API so applications can perform common video operations without manually constructing FFmpeg arguments.
Every processing call follows the same flow:
- Verify that FFmpeg is installed and that the input is a real video file (FFprobe).
- Verify that the output folder exists and validate the numeric arguments.
- Read the video duration so progress can be calculated.
- Build the FFmpeg arguments for the requested operation.
- Run FFmpeg with
-progress pipe:1and parse its progress output into your callback. - Resolve with the output path(s) when FFmpeg exits with code
0, or reject withFFmpegErrorotherwise.
Development
Clone the repository:
git clone https://github.com/abdu-selam/multi-media.git
cd multi-mediaInstall dependencies:
npm installBuild the package:
npm run buildThe compiled package is generated in the dist directory (ESM .mjs, CommonJS .cjs, and type declarations).
Available scripts:
| Script | Description |
| --------------- | --------------------------------------------- |
| npm run dev | Run the entry file in watch mode with tsx |
| npm run build | Build the package with tsdown |
| npm run check | Type-check the project without emitting files |
Project Structure
multi-media/
├── src/
│ ├── index.ts # Package entry point
│ ├── core/
│ │ ├── index.ts
│ │ └── video/
│ │ ├── Video.ts # Video class
│ │ └── statics.ts # Standalone helper functions
│ ├── commands/
│ │ ├── checking.ts # isVideo and FFmpeg/FFprobe availability checks
│ │ └── execute.ts # FFprobe and FFmpeg command runners
│ ├── data/
│ │ └── mimeTypes.ts # Format configs and FFmpeg argument builders
│ ├── errors/
│ │ └── video.error.ts # Custom error classes
│ ├── types/
│ │ └── video.types.ts # TypeScript types and interfaces
│ └── utils/ # File, terminal, validation, and formatting helpers
├── tsdown.config.ts
├── tsconfig.json
├── package.json
├── LICENSE
└── README.mdLicense
This project is licensed under the MIT License.
See the LICENSE file for details.
Author
Abduselam Awel
GitHub: https://github.com/abdu-selam
Repository
https://github.com/abdu-selam/multi-media
If you find the package useful, consider giving the repository a star (⭐).
