| .. | ||
| dist | ||
| src | ||
| test-downloads | ||
| package-lock.json | ||
| package.json | ||
| pnpm-lock.yaml | ||
| README.md | ||
| tsconfig.json | ||
| vitest.config.ts | ||
| webpack.config.js | ||
yt-dlp-wrapper
A TypeScript wrapper library for yt-dlp, a powerful command-line video downloader.
Features
- 🔄 Full TypeScript support with comprehensive type definitions
- 🧩 Modular architecture for easy integration into your projects
- 🔍 Zod validation for reliable input/output handling
- 📊 Structured logging with TSLog
- 🛠️ Command-line interface built with yargs
- ⚡ Promise-based API for easy async operations
- 🔧 Highly configurable with sensible defaults
- 🔄 Progress tracking for downloads
- 💼 Error handling with clear error messages
- 🎵 Audio extraction with MP3 conversion support
Prerequisites
Before using this library, ensure you have:
- Node.js (v14 or higher)
- yt-dlp installed on your system:
- Linux/macOS:
brew install yt-dlporpip install yt-dlp - Windows: Download from yt-dlp GitHub releases
- Linux/macOS:
- ffmpeg (required for MP3 conversion):
- Linux/macOS:
brew install ffmpegorapt install ffmpeg - Windows: Download from ffmpeg.org
- Linux/macOS:
Installation
# Using npm
npm install yt-dlp-wrapper
# Using yarn
yarn add yt-dlp-wrapper
# Using pnpm
pnpm add yt-dlp-wrapper
CLI Usage
The library includes a command-line interface for common operations:
Download a video
# Basic download
npx yt-dlp-wrapper download https://www.youtube.com/watch?v=dQw4w9WgXcQ
# Download with specific format
npx yt-dlp-wrapper download https://www.tiktok.com/@businessblurb/video/7479849082844892458 -f "best[height<=720]"
# Download to specific directory
npx yt-dlp-wrapper download https://youtu.be/dQw4w9WgXcQ --output-dir "./downloads"
# Download as MP3 audio only
npx yt-dlp-wrapper download https://youtu.be/dQw4w9WgXcQ --mp3
Get video information
# Basic info
npx yt-dlp-wrapper info https://www.youtube.com/watch?v=dQw4w9WgXcQ
# With JSON output
npx yt-dlp-wrapper info https://www.tiktok.com/@businessblurb/video/7479849082844892458 --dump-json
List available formats
npx yt-dlp-wrapper formats https://www.youtube.com/watch?v=dQw4w9WgXcQ
Help
# General help
npx yt-dlp-wrapper --help
# Command-specific help
npx yt-dlp-wrapper download --help
API Usage
Basic Usage
import { YtDlp } from 'yt-dlp-wrapper';
// Create a new instance with default options
const ytdlp = new YtDlp();
// Download a video
async function downloadVideo() {
try {
const filePath = await ytdlp.downloadVideo('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
console.log(`Video downloaded to: ${filePath}`);
} catch (error) {
console.error('Download failed:', error);
}
}
downloadVideo();
Download with Options
import { YtDlp } from 'yt-dlp-wrapper';
const ytdlp = new YtDlp();
async function downloadWithOptions() {
try {
const filePath = await ytdlp.downloadVideo('https://www.tiktok.com/@businessblurb/video/7479849082844892458', {
format: 'bestvideo[height<=720]+bestaudio/best[height<=720]',
format: 'bestvideo[height<=720]+bestaudio/best[height<=720]',
outputDir: './downloads',
filename: 'tiktok-video.mp4',
subtitles: true,
audioOnly: false,
// Add any other options as needed
console.log(`Video downloaded to: ${filePath}`);
} catch (error) {
console.error('Download failed:', error);
}
}
downloadWithOptions();
Get Video Information
import { YtDlp } from 'yt-dlp-wrapper';
const ytdlp = new YtDlp();
async function getVideoInfo() {
try {
const info = await ytdlp.getVideoInfo('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
console.log('Video title:', info.title);
console.log('Duration:', info.duration);
console.log('Uploader:', info.uploader);
// Access other properties as needed
} catch (error) {
console.error('Failed to get video info:', error);
}
}
getVideoInfo();
List Available Formats
import { YtDlp } from 'yt-dlp-wrapper';
const ytdlp = new YtDlp();
async function listFormats() {
try {
const formats = await ytdlp.listFormats('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
// Display all formats
formats.forEach(format => {
console.log(`Format ID: ${format.formatId}`);
console.log(`Resolution: ${format.resolution}`);
console.log(`Extension: ${format.extension}`);
console.log(`File size: ${format.filesize}`);
console.log('---');
});
} catch (error) {
console.error('Failed to list formats:', error);
}
}
listFormats();
Custom Configuration
import { YtDlp } from 'yt-dlp-wrapper';
// Create a new instance with custom options
const ytdlp = new YtDlp({
executablePath: '/usr/local/bin/yt-dlp', // Custom path to yt-dlp executable
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
verbose: true,
// Add other global options as needed
});
// Use as normal
ytdlp.downloadVideo('https://www.youtube.com/watch?v=dQw4w9WgXcQ')
.then(filePath => console.log(`Video downloaded to: ${filePath}`))
.catch(error => console.error('Download failed:', error));
MP3 Downloads
The library supports extracting audio from videos and converting to MP3 format. This functionality requires ffmpeg to be installed on your system.
MP3 Downloads via CLI
# Basic MP3 download
npx yt-dlp-wrapper download https://www.youtube.com/watch?v=dQw4w9WgXcQ --mp3
# MP3 download with specific output directory
npx yt-dlp-wrapper download https://youtu.be/dQw4w9WgXcQ --mp3 --output-dir "./music"
# MP3 download with custom filename
npx yt-dlp-wrapper download https://youtu.be/dQw4w9WgXcQ --mp3 --filename "my-song.mp3"
MP3 Downloads via API
import { YtDlp } from 'yt-dlp-wrapper';
const ytdlp = new YtDlp();
async function downloadAsMp3() {
try {
const filePath = await ytdlp.downloadVideo('https://www.youtube.com/watch?v=dQw4w9WgXcQ', {
audioOnly: true,
audioFormat: 'mp3',
outputDir: './music',
filename: 'audio-track.mp3'
});
console.log(`Audio downloaded to: ${filePath}`);
} catch (error) {
console.error('Audio download failed:', error);
}
}
downloadAsMp3();
Notes on MP3 Conversion
- MP3 conversion requires ffmpeg to be installed on your system
- If ffmpeg is not found, an error message will be shown
- The audio quality defaults to the best available
- Progress for both download and conversion will be displayed
Advanced Examples
Download Playlist
import { YtDlp } from 'yt-dlp-wrapper';
const ytdlp = new YtDlp();
async function downloadPlaylist() {
try {
const result = await ytdlp.downloadVideo('https://www.youtube.com/playlist?list=PLexamplelistID', {
outputDir: './playlists',
playlistItems: '1-5', // Only download the first 5 videos
limit: 5,
format: 'best[height<=480]' // Lower quality to save space
});
console.log(`Playlist downloaded to: ${result}`);
} catch (error) {
console.error('Playlist download failed:', error);
}
}
downloadPlaylist();
Progress Tracking
import { YtDlp } from 'yt-dlp-wrapper';
const ytdlp = new YtDlp();
async function downloadWithProgress() {
try {
const filePath = await ytdlp.downloadVideo('https://www.youtube.com/watch?v=dQw4w9WgXcQ', {
onProgress: (progress) => {
console.log(`Download progress: ${progress.percent}%`);
console.log(`Speed: ${progress.speed}`);
console.log(`ETA: ${progress.eta}`);
}
});
console.log(`Video downloaded to: ${filePath}`);
} catch (error) {
console.error('Download failed:', error);
}
}
downloadWithProgress();
Error Handling
The library provides detailed error information:
import { YtDlp, YtDlpError } from 'yt-dlp-wrapper';
const ytdlp = new YtDlp();
async function handleErrors() {
try {
await ytdlp.downloadVideo('https://invalid-url.com/video');
} catch (error) {
if (error instanceof YtDlpError) {
console.error(`YtDlp Error: ${error.message}`);
console.error(`Error Code: ${error.code}`);
console.error(`Command: ${error.command}`);
} else {
console.error('Unknown error:', error);
}
}
}
handleErrors();
API Reference
YtDlp Class
Constructor
new YtDlp(options?: YtDlpOptions)
YtDlpOptions:
| Option | Type | Description | Default |
|---|---|---|---|
| executablePath | string | Path to yt-dlp executable | 'yt-dlp' |
| userAgent | string | User agent to use for requests | Default browser UA |
| verbose | boolean | Enable verbose output | false |
| quiet | boolean | Suppress output | false |
Methods
downloadVideo(url, options?)
Downloads a video from the given URL.
getVideoInfo(url, options?)
Gets information about a video.
listFormats(url, options?)
Lists available formats for a video.
checkInstallation()
Verifies that yt-dlp is installed and working.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
- yt-dlp - The amazing tool this library wraps
- All the contributors to the open-source libraries used in this project