### Install without binary and provide custom binary later Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/configuration.md Demonstrates how to install the package skipping the binary download and then providing a custom binary path. ```bash YOUTUBE_DL_SKIP_DOWNLOAD=true npm install youtube-dl-exec cp /path/to/yt-dlp node_modules/youtube-dl-exec/bin/ ``` -------------------------------- ### GitHub Actions example for providing GITHUB_TOKEN Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/configuration.md Shows how to set the GITHUB_TOKEN secret in GitHub Actions for npm installation. ```yaml # GitHub Actions example env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: npm install youtube-dl-exec ``` -------------------------------- ### YOUTUBE_DL_DIR Environment Variable Usage Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/configuration.md Example of specifying a custom installation directory for the yt-dlp binary. ```bash YOUTUBE_DL_DIR="/usr/local/bin" npm install youtube-dl-exec ``` -------------------------------- ### Example Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/main.md Shows how to access constants like YOUTUBE_DL_PATH and YOUTUBE_DL_DIR. ```javascript const { constants } = require('youtube-dl-exec') console.log(constants.YOUTUBE_DL_PATH) // e.g., "/path/to/node_modules/youtube-dl-exec/bin/yt-dlp" console.log(constants.YOUTUBE_DL_DIR) // e.g., "/path/to/node_modules/youtube-dl-exec/bin" ``` -------------------------------- ### Install Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/README.md Install the youtube-dl-exec package using npm. ```bash $ npm install youtube-dl-exec --save ``` -------------------------------- ### YOUTUBE_DL_HOST Customization Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/constants.md Example of customizing YOUTUBE_DL_HOST using an environment variable during installation. ```bash YOUTUBE_DL_HOST="https://mirror.example.com/yt-dlp" npm install youtube-dl-exec ``` -------------------------------- ### Check Installation Configuration Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/constants.md Logs various installation configuration constants. ```javascript const { constants } = require('youtube-dl-exec') console.log('=== Installation Configuration ===') console.log(`Binary path: ${constants.YOUTUBE_DL_PATH}`) console.log(`Binary directory: ${constants.YOUTUBE_DL_DIR}`) console.log(`Platform: ${constants.YOUTUBE_DL_PLATFORM}`) console.log(`Download skipped: ${!!constants.YOUTUBE_DL_SKIP_DOWNLOAD}`) ``` -------------------------------- ### DEBUG Environment Variable Usage Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/configuration.md Example of enabling debug logging during npm installation. ```bash DEBUG="youtube-dl-exec*" npm install youtube-dl-exec ``` -------------------------------- ### YOUTUBE_DL_DIR Customization Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/constants.md Example of customizing YOUTUBE_DL_DIR using an environment variable during installation. ```bash YOUTUBE_DL_DIR="/usr/local/bin/yt-dlp-binaries" npm install youtube-dl-exec ``` -------------------------------- ### Usage Example Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/types.md An example of how to use the youtubedl function to fetch video information. ```javascript const info = await youtubedl('https://www.youtube.com/watch?v=dQw4w9WgXcQ', { dumpSingleJson: true, noWarnings: true, noCheckCertificates: true, preferFreeFormats: true, addHeader: ['referer:youtube.com', 'user-agent:googlebot'] }) ``` -------------------------------- ### Accessing constants object Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/configuration.md Example of how to import and use the constants object to get configuration paths and values. ```javascript const { constants } = require('youtube-dl-exec') console.log(constants.YOUTUBE_DL_PATH) console.log(constants.YOUTUBE_DL_DIR) console.log(constants.YOUTUBE_DL_FILE) console.log(constants.YOUTUBE_DL_PLATFORM) console.log(constants.YOUTUBE_DL_HOST) console.log(constants.YOUTUBE_DL_SKIP_DOWNLOAD) console.log(constants.GITHUB_TOKEN) ``` -------------------------------- ### YOUTUBE_DL_HOST Environment Variable Usage - Default (Latest Release) Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/configuration.md Example of installing youtube-dl-exec, which defaults to downloading from GitHub's latest release API. ```bash npm install youtube-dl-exec # Downloads from GitHub's latest release API ``` -------------------------------- ### Usage Example Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/types.md Example of how to use the youtubedl function to get video info with the dumpSingleJson flag and access properties from the Payload type. ```javascript const info = await youtubedl('https://www.youtube.com/watch?v=dQw4w9WgXcQ', { dumpSingleJson: true }) console.log(info.title) // Payload type console.log(info.duration) // number ``` -------------------------------- ### Timeout Example Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/configuration.md Demonstrates how to set a timeout and kill signal for the youtube-dl process. ```javascript const youtubedl = require('youtube-dl-exec') try { const result = await youtubedl( 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', { dumpSingleJson: true }, { timeout: 30000, killSignal: 'SIGKILL' } ) } catch (error) { console.error('Timeout or process failed:', error.message) } ``` -------------------------------- ### YOUTUBE_DL_FILENAME Customization Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/constants.md Example of customizing YOUTUBE_DL_FILENAME using an environment variable during installation. ```bash YOUTUBE_DL_FILENAME="yt-dlp-custom" npm install youtube-dl-exec # On Windows becomes: "yt-dlp-custom.exe" ``` -------------------------------- ### YOUTUBE_DL_PATH Customization Example Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/constants.md Example demonstrating how YOUTUBE_DL_PATH is affected by customizing YOUTUBE_DL_DIR and YOUTUBE_DL_FILENAME. ```bash YOUTUBE_DL_DIR="/usr/local/bin" YOUTUBE_DL_FILENAME="yt-dlp-v2" npm install # Results in: /usr/local/bin/yt-dlp-v2 ``` -------------------------------- ### YOUTUBE_DL_PLATFORM Customization Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/constants.md Example of overriding platform detection for YOUTUBE_DL_PLATFORM using an environment variable during installation. ```bash YOUTUBE_DL_PLATFORM="win32" npm install youtube-dl-exec ``` -------------------------------- ### Example Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/main.md Demonstrates updating the default yt-dlp binary and checking the result. ```javascript const { update } = require('youtube-dl-exec') // Update the default instance binary const result = await update() if (result.exitCode === 0) { console.log('yt-dlp updated successfully') } else { console.error('Update failed:', result.stderr) } ``` -------------------------------- ### Custom Runtime Path Example Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/configuration.md Demonstrates how to access the configured YOUTUBE_DL_DIR at runtime. ```javascript const { constants } = require('youtube-dl-exec') console.log(constants.YOUTUBE_DL_DIR) // Output: "/usr/local/bin" (if YOUTUBE_DL_DIR was set during install) ``` -------------------------------- ### Example: Custom Binary Path using constants Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/configuration.md Illustrates using the constants object alongside the create function for managing custom binary paths. ```javascript const { constants, create } = require('youtube-dl-exec') // Use default binary const defaultYT = require('youtube-dl-exec') // Use custom binary const customYT = create('/usr/local/bin/yt-dlp') console.log('Default binary path:', constants.YOUTUBE_DL_PATH) console.log('Custom binary path:', '/usr/local/bin/yt-dlp') ``` -------------------------------- ### Example Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/main.md Demonstrates creating a custom instance of youtube-dl-exec with a specified binary path and using it to fetch video information. ```javascript const { create } = require('youtube-dl-exec') // Create instance with custom binary const youtubedl = create('/usr/local/bin/yt-dlp') // Use it exactly like the default instance const info = await youtubedl('https://www.youtube.com/watch?v=dQw4w9WgXcQ', { dumpSingleJson: true }) // Access subprocess const subprocess = youtubedl.exec('https://www.youtube.com/watch?v=dQw4w9WgXcQ') ``` -------------------------------- ### Environment Variables Example Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/configuration.md Shows how to pass custom environment variables to the spawned youtube-dl process. ```javascript const result = await youtubedl( 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', { dumpSingleJson: true }, { env: { ...process.env, PATH: '/custom/path:' + process.env.PATH, http_proxy: 'http://proxy.example.com:8080' } } ) ``` -------------------------------- ### Get simple string output Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/main.md This example shows how to get the raw stdout string from yt-dlp, specifically the duration of a video. ```javascript const youtubedl = require('youtube-dl-exec') // Get simple string output const duration = await youtubedl('https://www.youtube.com/watch?v=dQw4w9WgXcQ', { getDuration: true }) console.log(duration) // e.g., "213.22" ``` -------------------------------- ### Windows Path Example Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/main.md Shows how to create a youtube-dl-exec instance with a Windows-style path, where spaces are automatically handled. ```javascript const { create } = require('youtube-dl-exec') // Paths with spaces are automatically quoted on Windows const youtubedl = create('C:\\Program Files\\yt-dlp\\yt-dlp.exe') await youtubedl('https://www.youtube.com/watch?v=dQw4w9WgXcQ', { dumpSingleJson: true }) ``` -------------------------------- ### Get Fixtures Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/types/README.md Command to run the script for getting the fixtures. ```bash $ node types/index.js ``` -------------------------------- ### Skip Python version check during installation Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/configuration.md Example of setting the YOUTUBE_DL_SKIP_PYTHON_CHECK environment variable to bypass the Python version check. ```bash YOUTUBE_DL_SKIP_PYTHON_CHECK=1 npm install youtube-dl-exec ``` -------------------------------- ### Process Control Example Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/main.md This example demonstrates how to control the subprocess created by `youtubedl.exec`, such as killing it after a timeout. ```javascript const subprocess = youtubedl.exec( 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', { dumpSingleJson: true } ) // Kill process after 30 seconds setTimeout(() => { subprocess.kill('SIGKILL') }, 30000) try { const result = await subprocess } catch (error) { console.error('Process was terminated') } ``` -------------------------------- ### Custom binary path Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/README.md Example of creating a youtube-dl-exec instance with a custom binary path. ```javascript const { create: createYoutubeDl } = require('youtube-dl-exec') const youtubedl = createYoutubeDl('/my/binary/path') ``` -------------------------------- ### Example Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/main.md Illustrates converting a flags object into an array of command-line arguments for yt-dlp. ```javascript const { args } = require('youtube-dl-exec') const flags = args({ noWarnings: true, preferFreeFormats: true, addHeader: ['referer:youtube.com', 'user-agent:googlebot'], cacheDir: '/tmp/yt-cache' }) console.log(flags) // Output: // [ // '--no-warnings', // '--prefer-free-formats', // '--add-header', // 'referer:youtube.com', // '--add-header', // 'user-agent:googlebot', // '--cache-dir', // '/tmp/yt-cache' // ] ``` -------------------------------- ### GITHUB_TOKEN When Used Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/constants.md Example of setting the GITHUB_TOKEN environment variable during npm install to use a token for GitHub API requests. ```bash GITHUB_TOKEN="ghp_xxx..." npm install youtube-dl-exec # Token is used in Authorization header for GitHub API requests ``` -------------------------------- ### Provide GitHub token for authentication Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/configuration.md Demonstrates how to set GITHUB_TOKEN or GH_TOKEN environment variables for authenticating with the GitHub API during installation. ```bash GITHUB_TOKEN="ghp_xxx..." npm install youtube-dl-exec # or GH_TOKEN="ghp_xxx..." npm install youtube-dl-exec ``` -------------------------------- ### Basic Implementation Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/usage-patterns.md Get complete information about a video as a structured object. ```javascript const youtubedl = require('youtube-dl-exec') async function getVideoInfo(url) { try { const info = await youtubedl(url, { dumpSingleJson: true, noCheckCertificates: true, noWarnings: true, preferFreeFormats: true }) return { id: info.id, title: info.title, duration: info.duration, uploader: info.uploader, viewCount: info.view_count, uploadDate: info.upload_date, description: info.description, formats: info.formats, thumbnails: info.thumbnails } } catch (error) { throw new Error(`Failed to fetch video info: ${error.message}`) } } // Usage const info = await getVideoInfo('https://www.youtube.com/watch?v=dQw4w9WgXcQ') console.log(info.title) ``` -------------------------------- ### YOUTUBE_DL_SKIP_DOWNLOAD When Set Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/constants.md Example of setting the YOUTUBE_DL_SKIP_DOWNLOAD environment variable during npm install to skip automatic download. ```bash YOUTUBE_DL_SKIP_DOWNLOAD=true npm install youtube-dl-exec # Skips automatic download ``` -------------------------------- ### YOUTUBE_DL_PLATFORM Usage Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/constants.md Example of how to access the YOUTUBE_DL_PLATFORM constant. ```javascript const { constants } = require('youtube-dl-exec') console.log(constants.YOUTUBE_DL_PLATFORM) // "unix" or "win32" ``` -------------------------------- ### Progress bar integration Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/README.md Example of integrating youtube-dl-exec with a progress estimator library. ```javascript const logger = require('progress-estimator')() const youtubedl = require('youtube-dl-exec') const url = 'https://www.youtube.com/watch?v=6xKWiCMKKJg' const promise = youtubedl(url, { dumpSingleJson: true }) const result = await logger(promise, `Obtaining ${url}`) console.log(result) ``` -------------------------------- ### Provide Custom Binary Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/constants.md Example of creating a youtube-dl-exec instance with a custom binary path. ```javascript const { create } = require('youtube-dl-exec') // Check if custom binary exists const customBinaryPath = '/usr/local/bin/yt-dlp' const youtubedl = create(customBinaryPath) const info = await youtubedl('https://www.youtube.com/watch?v=dQw4w9WgXcQ', { dumpSingleJson: true }) ``` -------------------------------- ### YOUTUBE_DL_PLATFORM Environment Variable Usage - Force Windows Binary Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/configuration.md Example of forcing the download of the Windows binary even on a Unix-like system. ```bash # Force Windows binary even on Unix system YOUTUBE_DL_PLATFORM="win32" npm install youtube-dl-exec ``` -------------------------------- ### YOUTUBE_DL_HOST Usage Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/constants.md Example of how to access the YOUTUBE_DL_HOST constant. ```javascript const { constants } = require('youtube-dl-exec') console.log(constants.YOUTUBE_DL_HOST) // "https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest" ``` -------------------------------- ### Skipping download during installation Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/README.md Shows how to set the YOUTUBE_DL_SKIP_DOWNLOAD environment variable to skip the postinstall script for fetching the yt-dlp version. ```bash YOUTUBE_DL_SKIP_DOWNLOAD=true npm install ``` -------------------------------- ### YOUTUBE_DL_FILE Usage Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/constants.md Example of how to access the YOUTUBE_DL_FILE constant. ```javascript const { constants } = require('youtube-dl-exec') console.log(constants.YOUTUBE_DL_FILE) // "yt-dlp" on Unix // "yt-dlp.exe" on Windows ``` -------------------------------- ### YOUTUBE_DL_PLATFORM Environment Variable Usage - Force Unix Binary Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/configuration.md Example of forcing the download of the Unix binary even on a Windows system. ```bash # Force Unix binary even on Windows YOUTUBE_DL_PLATFORM="unix" npm install youtube-dl-exec ``` -------------------------------- ### YOUTUBE_DL_DIR Usage Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/constants.md Example of how to access the YOUTUBE_DL_DIR constant. ```javascript const { constants } = require('youtube-dl-exec') console.log(constants.YOUTUBE_DL_DIR) // e.g., "/home/user/node_modules/youtube-dl-exec/bin" ``` -------------------------------- ### Timeout and cancellation Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/README.md Example of setting a timeout and kill signal for the yt-dlp process. ```javascript const url = 'https://www.youtube.com/watch?v=6xKWiCMKKJg' const result = await youtubedl.exec(url, ,{ dumpSingleJson: true }, { timeout: 5000, killSignal: 'SIGKILL' }) console.log(result) ``` -------------------------------- ### YOUTUBE_DL_HOST Environment Variable Usage - Custom Mirror Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/configuration.md Example of specifying a custom mirror URL for downloading the yt-dlp binary. ```bash YOUTUBE_DL_HOST="https://mirror.example.com/yt-dlp/latest" npm install youtube-dl-exec ``` -------------------------------- ### YOUTUBE_DL_FILENAME Environment Variable Usage Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/configuration.md Example of specifying a custom filename for the yt-dlp binary. ```bash YOUTUBE_DL_FILENAME="yt-dlp-custom" npm install youtube-dl-exec ``` -------------------------------- ### Listing Available Formats Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/errors.md Shows how to use the `listFormats` option to get raw output of available video formats. ```javascript try { const output = await youtubedl(url, { listFormats: true // Don't parse, get raw output }) // output.stdout contains the format list } catch (error) { // ... } ``` -------------------------------- ### YOUTUBE_DL_HOST Environment Variable Usage - Specific Release Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/configuration.md Example of specifying a direct URL to a specific release of the yt-dlp binary. ```bash YOUTUBE_DL_HOST="https://github.com/yt-dlp/yt-dlp/releases/download/2026.03.17/yt-dlp" npm install youtube-dl-exec ``` -------------------------------- ### Programmatic subprocess interaction Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/README.md Example of interacting with the yt-dlp subprocess programmatically for cancellation. ```javascript const url = 'https://www.youtube.com/watch?v=6xKWiCMKKJg' const subprocess = youtubedl.exec(url, { dumpSingleJson: true }) setTimeout(() => { subprocess.kill('SIGKILL') }, 5000) const result = await subprocess console.log(result) ``` -------------------------------- ### Usage Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/README.md Example of using youtube-dl-exec to download video information as a JSON object. ```javascript const youtubedl = require('youtube-dl-exec') youtubedl('https://www.youtube.com/watch?v=6xKWiCMKKJg', { dumpSingleJson: true, noCheckCertificates: true, noWarnings: true, preferFreeFormats: true, addHeader: ['referer:youtube.com', 'user-agent:googlebot'] }).then(output => console.log(output)) ``` -------------------------------- ### Testing Binary Not Found (ENOENT) Error Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/errors.md Example using AVA to test for the 'ENOENT' error. ```javascript const test = require('ava') const youtubedl = require('youtube-dl-exec') test.serial('catch errors', async t => { // Temporarily rename the binary const error = await t.throwsAsync(youtubedl(''), { instanceOf: Error }) t.is(error.code, 'ENOENT') }) ``` -------------------------------- ### Equivalent CLI command Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/README.md The equivalent command-line interface command for the JavaScript usage example. ```bash ./bin/yt-dlp \ --dump-single-json \ --no-check-certificates \ --no-warnings \ --prefer-free-formats \ --add-header='user-agent:googlebot' \ --add-header='referer:youtube.com' \ 'https://www.youtube.com/watch?v=6xKWiCMKKJg' ``` -------------------------------- ### YOUTUBE_DL_PATH Usage Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/constants.md Example of how to access the YOUTUBE_DL_PATH constant and its internal use. ```javascript const { constants } = require('youtube-dl-exec') console.log(constants.YOUTUBE_DL_PATH) // Used internally as the default binary path: const defaultInstance = create(constants.YOUTUBE_DL_PATH) ``` -------------------------------- ### Fetch and parse video metadata Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/main.md This example demonstrates how to fetch and parse video metadata using the `youtubedl` function. ```javascript const youtubedl = require('youtube-dl-exec') // Fetch and parse video metadata const info = await youtubedl('https://www.youtube.com/watch?v=dQw4w9WgXcQ', { dumpSingleJson: true, noWarnings: true, noCheckCertificates: true }) console.log(info.title) console.log(info.duration) ``` -------------------------------- ### Example Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/main.md Demonstrates using the isJSON function to check if a string is valid JSON. ```javascript const { isJSON } = require('youtube-dl-exec') console.log(isJSON('{"title": "Video"}')) // true console.log(isJSON('Some text output')) // false ``` -------------------------------- ### Executing youtube-dl with exec Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/README.md Demonstrates how to use the `exec` method to get the internal subprocess object, pipe stdout and stderr, and cancel the process after a timeout. ```javascript const youtubedl = require('youtube-dl-exec') const fs = require('fs') const subprocess = youtubedl.exec( 'https://www.youtube.com/watch?v=6xKWiCMKKJg', { dumpSingleJson: true } ) console.log(`Running subprocess as ${subprocess.pid}`) subprocess.stdout.pipe(fs.createWriteStream('stdout.txt')) subprocess.stderr.pipe(fs.createWriteStream('stderr.txt')) setTimeout(subprocess.cancel, 30000) ``` -------------------------------- ### Error Handling Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/main.md This example demonstrates how to handle errors when executing the `youtubedl` function. ```javascript const youtubedl = require('youtube-dl-exec') try { await youtubedl('https://www.apple.com/homepod', { dumpSingleJson: true }) } catch (error) { console.error(error.message) // "ERROR: Unsupported URL: ..." console.error(error.stderr) console.error(error.exitCode) // non-zero } ``` -------------------------------- ### YOUTUBE_DL_SKIP_DOWNLOAD Usage Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/constants.md Example of how to check the YOUTUBE_DL_SKIP_DOWNLOAD constant to see if binary download was skipped. ```javascript const { constants } = require('youtube-dl-exec') if (constants.YOUTUBE_DL_SKIP_DOWNLOAD) { console.log('Binary download was skipped during install') console.log('Ensure yt-dlp binary is available at:', constants.YOUTUBE_DL_PATH) } ``` -------------------------------- ### Catching No URL Provided Error Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/errors.md Example of how to catch the error when no URL is provided to the library. ```javascript const youtubedl = require('youtube-dl-exec') try { await youtubedl('') // Empty URL } catch (error) { if (error.exitCode === 2) { console.error('You must provide a URL') } } ``` -------------------------------- ### Basic Playlist Download Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/usage-patterns.md Download multiple videos from a playlist, specifying start and end points. ```javascript async function downloadPlaylist(url, outputPath, start = 1, end = null) { const flags = { yesPlaylist: true, format: 'best[height<=720]/best', output: `${outputPath}/%(playlist)s/%(playlist_index)03d - %(title)s.%(ext)s`, playlistStart: start } if (end) { flags.playlistEnd = end } await youtubedl(url, flags) } // Usage await downloadPlaylist( 'https://www.youtube.com/playlist?list=PLxxx', './videos', 1, 10 ) ``` -------------------------------- ### Catching Binary Not Found (ENOENT) Error Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/errors.md Example of how to catch the 'ENOENT' error when the yt-dlp binary is not found. ```javascript const youtubedl = require('youtube-dl-exec') try { const result = await youtubedl('https://www.youtube.com/watch?v=dQw4w9WgXcQ') } catch (error) { if (error.code === 'ENOENT') { console.error(`Binary not found at: ${error.path}`) console.error('Install the package or provide YOUTUBE_DL_SKIP_DOWNLOAD=false') } } ``` -------------------------------- ### Timeout Control Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/usage-patterns.md Example of how to implement a timeout for a download operation, including graceful and forceful termination of the subprocess. ```javascript async function downloadWithTimeout(url, timeoutMs = 60000) { const subprocess = youtubedl.exec(url, { format: 'best', output: '%(title)s.%(ext)s' }) const timeoutHandle = setTimeout(() => { console.log('Timeout exceeded, killing process...') subprocess.kill('SIGTERM') // Graceful kill first setTimeout(() => { subprocess.kill('SIGKILL') // Force kill if needed }, 5000) }, timeoutMs) try { const result = await subprocess clearTimeout(timeoutHandle) return result } catch (error) { clearTimeout(timeoutHandle) if (error.signal === 'SIGTERM' || error.signal === 'SIGKILL') { throw new Error('Download timed out') } throw error } } ``` -------------------------------- ### Create custom instance with a specific binary path Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/configuration.md Shows how to create a new instance of youtube-dl-exec pointing to a custom binary. ```javascript const { create } = require('youtube-dl-exec') const youtubedl = create('/custom/path/to/yt-dlp') ``` -------------------------------- ### Create Custom Instance Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/usage-patterns.md Demonstrates how to create custom instances of the youtube-dl-exec library using different paths to the yt-dlp binary. ```javascript const { create } = require('youtube-dl-exec') const path = require('path') // Use system-installed yt-dlp const yt1 = create('/usr/local/bin/yt-dlp') // Use project-local binary const yt2 = create(path.join(__dirname, 'binaries', 'yt-dlp')) // Use version-specific binary const yt3 = create('/opt/yt-dlp/v2026.03.17/yt-dlp') // All three behave identically const info = await yt1(url, { dumpSingleJson: true }) ``` -------------------------------- ### Access the subprocess and stream output Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/main.md This example shows how to use `youtubedl.exec` to get the underlying subprocess object and stream its output. ```javascript const youtubedl = require('youtube-dl-exec') // Access the subprocess and stream output const subprocess = youtubedl.exec( 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', { dumpSingleJson: true } ) console.log(`Process ID: ${subprocess.pid}`) // Pipe to file const fs = require('fs') subprocess.stdout.pipe(fs.createWriteStream('output.json')) // Wait for completion const result = await subprocess console.log(result.exitCode) // 0 if successful ``` -------------------------------- ### Auto-Detection Logic for YOUTUBE_DL_PLATFORM Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/configuration.md Illustrates the JavaScript logic used to auto-detect the platform for binary download. ```javascript const YOUTUBE_DL_PLATFORM = isUnix(process.platform) ? 'unix' : 'win32' ``` -------------------------------- ### File Manifest Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/README.md Directory structure of the documentation files. ```bash output/ ├── README.md ← You are here ├── INDEX.md ← Start here for overview ├── types.md ← Type definitions ├── configuration.md ← Environment variables ├── errors.md ← Error handling ├── flags-reference.md ← All 100+ flags ├── usage-patterns.md ← 12 practical patterns └── api-reference/ ├── main.md ← Core API functions └── constants.md ← Binary path constants ``` -------------------------------- ### YOUTUBE_DL_FILENAME Usage Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/constants.md Example of how to access the YOUTUBE_DL_FILENAME constant. ```javascript const { constants } = require('youtube-dl-exec') console.log(constants.YOUTUBE_DL_FILENAME) // "yt-dlp" or "yt-dlp.exe" ``` -------------------------------- ### JSON Detection Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/INDEX.md Output is automatically parsed as JSON if it starts with `{`. ```javascript const result = await youtubedl(url, { dumpSingleJson: true }) console.log(typeof result) // "object" - parsed JSON console.log(result.title) // works const title = await youtubedl(url, { getTitle: true }) console.log(typeof title) // "string" - not parsed ``` -------------------------------- ### With Metadata Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/usage-patterns.md Download audio with embedded metadata, info JSON, and thumbnail. ```javascript async function downloadAudioWithMetadata(url, outputPath) { await youtubedl(url, { extractAudio: true, audioFormat: 'mp3', audioQuality: 0, addMetadata: true, writeInfoJson: true, embedThumbnail: true, output: `${outputPath}/%(title)s.%(ext)s` }) } ``` -------------------------------- ### Playlist with Progress Monitoring Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/usage-patterns.md Download a playlist and monitor the overall download progress. ```javascript async function downloadPlaylistWithProgress(url, outputPath) { const subprocess = youtubedl.exec(url, { yesPlaylist: true, format: 'best', output: `${outputPath}/%(title)s.%(ext)s` }) let downloadedCount = 0 const progressRegex = /%download% (\d+\.\d+)%/ subprocess.stderr.on('data', (chunk) => { const match = chunk.toString().match(progressRegex) if (match) { const percent = parseFloat(match[1]) console.log(`Overall progress: ${percent}%`) } }) const result = await subprocess console.log('Playlist download complete') return result } ``` -------------------------------- ### Catching Unsupported URL Error Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/errors.md Example of how to catch the 'Unsupported URL' error. ```javascript const youtubedl = require('youtube-dl-exec') try { await youtubedl('https://www.apple.com/homepod', { dumpSingleJson: true, noWarnings: true }) } catch (error) { if (error.message.includes('Unsupported URL')) { console.error(`URL not supported: ${error.message}`) } } ``` -------------------------------- ### Valid Cases (no URL needed) Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/errors.md Examples of valid calls that do not require a URL. ```javascript // These work without a URL const result = await youtubedl('', { version: true // Just get version }) const result = await youtubedl('', { help: true // Get help }) ``` -------------------------------- ### Custom Binary Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/INDEX.md Create a custom instance of the library pointing to a specific yt-dlp binary path. ```javascript const { create } = require('youtube-dl-exec') const youtubedl = create('/custom/path/to/yt-dlp') const info = await youtubedl(url, { dumpSingleJson: true }) ``` -------------------------------- ### Access Subprocess Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/INDEX.md Get the raw subprocess object for streaming or advanced control. ```javascript // Get raw subprocess for streaming const subprocess = youtubedl.exec(url, { dumpSingleJson: true }) console.log(`PID: ${subprocess.pid}`) subprocess.stdout.pipe(fs.createWriteStream('output.json')) const result = await subprocess console.log(result.exitCode) ``` -------------------------------- ### Type-Safe Usage (TypeScript) Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/usage-patterns.md Illustrates how to use `youtube-dl-exec` with TypeScript for enhanced type safety, including fetching metadata and downloading videos with specific quality settings. ```typescript import youtubedl, { Flags, Payload, create, update } from 'youtube-dl-exec' async function getVideoMetadata(url: string): Promise { const flags: Flags = { dumpSingleJson: true, noCheckCertificates: true, noWarnings: true, preferFreeFormats: true } return await youtubedl(url, flags) } async function downloadVideo(url: string, quality: number): Promise { const heightMap = { 1: '720', 2: '1080', 3: '2160' } const height = heightMap[quality] || '720' const flags: Flags = { format: `best[height<=${height}]`, output: '%(title)s.%(ext)s', writeInfoJson: true, writeThumbnail: true } await youtubedl(url, flags) } // Usage const metadata: Payload = await getVideoMetadata('https://...') console.log(metadata.title) await downloadVideo('https://...', 2) ``` -------------------------------- ### Simple File-Based Cache Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/usage-patterns.md A JavaScript class demonstrating how to implement a file-based cache for video metadata to avoid re-fetching information. ```javascript const fs = require('fs').promises const path = require('path') const youtubedl = require('youtube-dl-exec') class VideoInfoCache { constructor(cacheDir = './cache') { this.cacheDir = cacheDir } getCachePath(videoId) { return path.join(this.cacheDir, `${videoId}.json`) } async get(url) { // Extract video ID from URL const videoId = new URL(url).searchParams.get('v') || url.split('/').pop() const cachePath = this.getCachePath(videoId) // Try cache first try { const cached = await fs.readFile(cachePath, 'utf-8') return JSON.parse(cached) } catch (error) { // Cache miss, fetch from yt-dlp } // Fetch and cache const info = await youtubedl(url, { dumpSingleJson: true, noWarnings: true }) await fs.mkdir(this.cacheDir, { recursive: true }) await fs.writeFile(cachePath, JSON.stringify(info, null, 2)) return info } async clear() { const files = await fs.readdir(this.cacheDir) for (const file of files) { await fs.unlink(path.join(this.cacheDir, file)) } } } // Usage const cache = new VideoInfoCache('./video-cache') const info = await cache.get('https://www.youtube.com/watch?v=dQw4w9WgXcQ') ``` -------------------------------- ### GITHUB_TOKEN Usage Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/constants.md Example of how to check the GITHUB_TOKEN constant to see if GitHub authentication is enabled. ```javascript const { constants } = require('youtube-dl-exec') if (constants.GITHUB_TOKEN) { console.log('GitHub authentication is enabled') } ``` -------------------------------- ### Import Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/INDEX.md Import the library using CommonJS or ES Modules syntax. ```javascript const youtubedl = require('youtube-dl-exec') // TypeScript import youtubedl from 'youtube-dl-exec' ``` -------------------------------- ### Update Custom Binary Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/api-reference/main.md Shows how to update a specific yt-dlp binary located at a custom path. ```javascript const { update } = require('youtube-dl-exec') // Update specific binary const result = await update('/usr/local/bin/yt-dlp') console.log(result.stdout) ``` -------------------------------- ### List Available Formats Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/usage-patterns.md Fetches and displays available video/audio formats for a given URL, including format ID, resolution, codecs, and approximate file size. ```javascript async function listFormats(url) { const info = await youtubedl(url, { dumpSingleJson: true, skipDownload: true }) console.log('Available formats:') for (const format of info.formats) { const res = format.resolution || 'audio' const codec = `${format.vcodec} / ${format.acodec}` const size = format.filesize_approx ? `${Math.round(format.filesizeize_approx / 1024 / 1024)}MB` : 'unknown' console.log(`[${format.format_id}] ${res} ${codec} (${size})`) } return info.formats } ``` -------------------------------- ### Basic Usage Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/INDEX.md Get video metadata by providing a URL and options. The output is automatically parsed JSON. ```javascript // Get video metadata const info = await youtubedl('https://www.youtube.com/watch?v=dQw4w9WgXcQ', { dumpSingleJson: true }) console.log(info.title) console.log(info.duration) console.log(info.formats) // All available formats ``` -------------------------------- ### Load Info from Previously Cached JSON Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/usage-patterns.md Demonstrates how to use the `loadInfoJson` option to download a video using metadata from a previously cached JSON file, avoiding re-fetching. ```javascript async function downloadUsingCachedInfo(infoJsonPath, outputPath) { // Using an empty URL with loadInfoJson flag // tells yt-dlp to use the cached metadata await youtubedl('', { loadInfoJson: infoJsonPath, format: 'best[height<=720]', output: `${outputPath}/%(title)s.%(ext)s`, writeInfoJson: true }) } // First, fetch and cache the info const info = await youtubedl(url, { dumpSingleJson: true, writeInfoJson: true, output: '%(title)s.info.json' }) // Later, reuse the cached info await downloadUsingCachedInfo('video-title.info.json', './downloads') ``` -------------------------------- ### Basic Audio Download Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/usage-patterns.md Extract audio from a video and save it as an MP3 file. ```javascript const youtubedl = require('youtube-dl-exec') async function downloadAudio(url, outputPath) { try { await youtubedl(url, { extractAudio: true, audioFormat: 'mp3', audioQuality: 0, // 0 = best, 9 = worst output: `${outputPath}/%(title)s.%(ext)s` }) console.log('Audio downloaded successfully') } catch (error) { console.error('Download failed:', error.message) throw error } } // Usage await downloadAudio('https://www.youtube.com/watch?v=dQw4w9WgXcQ', './downloads') ``` -------------------------------- ### With Custom Headers (Bypass Restrictions) Source: https://github.com/microlinkhq/youtube-dl-exec/blob/master/_autodocs/usage-patterns.md Fetch video metadata using custom headers to bypass potential restrictions. ```javascript async function getVideoInfoWithHeaders(url) { const info = await youtubedl(url, { dumpSingleJson: true, noCheckCertificates: true, noWarnings: true, addHeader: [ 'referer:youtube.com', 'user-agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ] }) return info } ```