youtube-dl-exec

repository·master·Indexed 20 days ago

https://github.com/microlinkhq/youtube-dl-exec

A Node.js wrapper for yt-dlp (version 3.1.10) that provides Promise and Stream interfaces. It supports auto-installation of the latest yt-dlp version, custom binary paths via .create(), and binary updates via .update(). The library allows for easy configuration of yt-dlp flags and subprocess control through .exec(), requiring Python 3.9 or above as a system prerequisite.

Tokens
3.5K
Snippets
14
Records
17
Agent score
70%

What's inside youtube-dl-exec

  1. Handle timeouts and cancellation

    master

    You can manage process lifecycles in two ways:

    1. Via options: Pass timeout and killSignal as the third argument to youtubedl.exec() (which maps to spawn#options).
    2. Programmatically: Use the subprocess object returned by youtubedl.exec() to call .kill() or .cancel().

    Note: The main youtubedl() function returns a Promise, while youtubedl.exec() returns the subprocess object.

    // Method 1: Using spawn options
    const url = 'https://www.youtube.com/watch?v=6xKWiCMKKJg'
    const result = await youtubedl.exec(url, ,{ dumpSingleJson: true }, {
      timeout: 5000,
      killSignal: 'SIGKILL'
    })
    
    // Method 2: Manual cancellation
    const subprocess = youtubedl.exec(url, { dumpSingleJson: true })
    
    setTimeout(() => {
      subprocess.kill('SIGKILL')
    }, 5000)
    
    const result = await subprocess
  2. Install youtube-dl-exec

    master

    Install the package via npm.

    Prerequisite: Your system must have python3 (Python 3.9 or above) available. If Python 3.9+ is not found, the library will throw an error.

    By default, the library auto-installs the latest yt-dlp version during the build process.

    $ npm install youtube-dl-exec --save
  3. How to generate types

    master

    If you are contributing to the project or need to regenerate the TypeScript definitions based on the current fixtures, follow these steps:

    1. Execute the fixture collection script:
      node types/index.js
    2. Use the generated fixtures at app.quicktype.io to generate the TypeScript interfaces.
    3. Replace the existing types in src/index.d.ts with the newly generated ones.
    $ node types/index.js
  4. Install yt-dlp plugins

    master

    To use yt-dlp plugins, you must place a plugin.zip file inside a yt-dlp-plugins directory located under the same path as your yt-dlp binary.

    If using the default installation, the path is: node_modules/youtube-dl-exec/bin/yt-dlp-plugins/plugin.zip

  5. Understand the Payload data structure

    master

    When using flags like --dump-json or --print-json, the library returns a Payload object. This object contains comprehensive metadata about the video, audio, or playlist being processed.

    Key Payload Fields

    • Metadata: id, title, description, view_count, like_count, comment_count, upload_date, timestamp.
    • Channel Info: channel, channel_id, channel_url, channel_follower_count.
    • Media Info: duration, duration_string, is_live, was_live, media_type, webpage_url.
    • Formats: formats (an array of Format objects) and requested_formats.
    • Thumbnails: thumbnails (array) and thumbnail (string URL).
    • Subtitles: subtitles and automatic_captions.
    • Technical Details: ext (extension), vcodec, acodec, resolution, fps, width, height, filesize_approx.

    Format Object

    Each item in the formats array is a Format object containing specific details about a stream, such as its protocol, abr (audio bitrate), vbr (video bitrate), and url.

    // Example of accessing Payload properties
    type Payload = {
      id: string;
      title: string;
      formats: Format[];
      thumbnails: Thumbnail[];
      // ... other fields
    };
  6. Basic usage with youtubedl()

    master

    The main function youtubedl(url, [flags], [options]) executes a yt-dlp command and returns the output (usually parsed JSON if requested).

    • url: The target URL (string).
    • flags: An object where keys represent yt-dlp flags (e.g., { dumpSingleJson: true }).
    • options: An object passed to Node.js spawn#options for process control.
    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))
  7. Access the subprocess with youtubedl.exec()

    master

    If you need granular control over the process (like streaming stdout/stderr or interacting with the PID), use youtubedl.exec(). Unlike the main function, this returns the internal subprocess object instead of the parsed output.

    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'))
    
    // You can also cancel the subprocess
    setTimeout(subprocess.cancel, 30000)
  8. Convert flag objects to CLI arguments with args()

    master

    The args(flags) utility converts a JavaScript object into an array of command-line arguments. It uses dargs with { useEquals: false }, meaning flags like { format: 'mp4' } will be converted to ['--format', 'mp4'] rather than --format=mp4.

    const { args } = require('youtube-dl-exec');
    
    const cliArgs = args({ format: 'best', dumpJson: true });
    // Result: ['--format', 'best', '--dump-json']
  9. Use youtubeDl.exec() for command execution

    master

    The exec method on the default instance (or any instance created via create) allows you to run commands with a specific URL, a flags object, and an options object. The flags object is converted into command-line arguments using dargs. If you are on Windows and the binary path contains spaces, shell: true is automatically enabled in the options.

    const { youtubeDl } = require('youtube-dl-exec');
    
    // Signature: exec(url, flags, opts = {})
    await youtubeDl.exec('https://example.com', { '--list-formats': true }, { timeout: 10000 });
  10. Execute youtube-dl commands with the default instance

    master

    The main export of the package is a pre-configured instance that uses the default youtube-dl binary path. You can call this instance directly to execute commands. It accepts a URL and a flags object. The output is automatically parsed: if the command returns JSON, it returns a parsed object; otherwise, it returns the raw stdout string. If the command fails (non-zero exit code), it throws an error containing stderr, stdout, and the exitCode.

    const youtubeDl = require('youtube-dl-exec');
    
    // Basic usage
    const data = await youtubeDl('https://www.youtube.com/watch?v=dQw4w9WgXcQ', {
      dumpJson: true,
      format: 'best'
    });
    
    console.log(data);