@distube/ytdl-core

repository·master·Indexed 19 days ago

https://github.com/distubejs/ytdl-core

A maintained fork of ytdl-core and a pure JavaScript YouTube video downloader. It provides functionality to download video streams via ytdl(), retrieve metadata using getInfo() and getBasicInfo(), and manage downloads with downloadFromInfo(). The library includes utilities for format selection, URL/ID validation, and support for cookies and proxies to handle authentication and regional restrictions.

Tokens
3.2K
Snippets
11
Records
16
Agent score
18%

What's inside @distube/ytdl-core

  1. Configure Cookies Support

    master

    To access private videos, rentals, or YouTube Premium content, you must provide cookies. You can export cookies from your browser using the EditThisCookie extension and pass them to ytdl.createAgent.

    Important Security Notes:

    • Use a dedicated account for this purpose.
    • Do not use the YouTube 'logout' button; instead, delete browser cookies or use incognito mode to avoid expiring the session prematurely.
    • Ensure the account is only using one IP address at a time to keep cookies alive longer.

    You can pass cookies as an array of objects or read them from a JSON file.

    const ytdl = require("@distube/ytdl-core");
    const fs = require("fs");
    
    // Option 1: Using a hardcoded array (not recommended for production)
    const cookies = [
      { name: "cookie1", value: "COOKIE1_HERE" },
      { name: "cookie2", value: "COOKIE2_HERE" },
    ];
    const agent = ytdl.createAgent(cookies);
    
    // Option 2: Reading from a JSON file
    const agentFromFile = ytdl.createAgent(JSON.parse(fs.readFileSync("cookies.json")));
    
    // Use the agent in requests
    ytdl.getInfo("http://www.youtube.com/watch?v=aqz-KE-bpKQ", { agent: agentFromFile });
  2. Install @distube/ytdl-core

    master

    Install the latest version of @distube/ytdl-core using npm. It is highly recommended to always use the latest version to keep up with YouTube's frequent changes and fixes.

    npm install @distube/ytdl-core@latest
  3. Implement IP Rotation

    master

    The built-in getRandomIPv6 utility is deprecated and will be removed. To implement IP rotation, you should create a unique ytdl.Agent for each IP address by assigning the desired IP to the localAddress property within the undici agent options.

    const ytdl = require("@distube/ytdl-core");
    const { getRandomIPv6 } = require("@distube/ytdl-core/lib/utils");
    
    // Create an agent for a specific random IPv6 address
    const agentForARandomIP = ytdl.createAgent(undefined, {
      localAddress: getRandomIPv6("2001:2::/48"),
    });
    
    ytdl.getBasicInfo("http://www.youtube.com/watch?v=aqz-KE-bpKQ", { agent: agentForARandomIP });
  4. Configure Proxy Support

    master

    To bypass regional restrictions or handle rate limiting, use ytdl.createProxyAgent. You can also combine proxies with cookies by passing the cookies array as the second argument to createProxyAgent.

    const ytdl = require("@distube/ytdl-core");
    
    // Proxy only
    const agent = ytdl.createProxyAgent({ uri: "my.proxy.server" });
    
    // Proxy with cookies
    const agentWithCookies = ytdl.createProxyAgent(
      { uri: "my.proxy.server" }, 
      [{ name: "cookie", value: "COOKIE_HERE" }]
    );
    
    ytdl.getInfo("http://www.youtube.com/watch?v=aqz-KE-bpKQ", { agent: agentWithCookies });
  5. Disable Update Checks

    master

    The library checks for updates every 12 hours and prints a warning if an update is available. To disable this behavior, set the YTDL_NO_UPDATE environment variable to 1.

    env YTDL_NO_UPDATE=1 node myapp.js
  6. Troubleshooting: Rate Limiting (HTTP 429)

    master

    If YouTube blocks your requests with an HTTP 429 status code, try the following:

    1. Update: Ensure you are using the latest version of @distube/ytdl-core.
    2. Proxies: Use proxies to distribute requests across different IP addresses.
    3. IP Rotation: Implement IPv6 address rotation.
    4. Cookies: Use cookies (Note: You must wait for the current rate limit to expire before applying cookies for them to be effective).
    5. Wait: If all else fails, wait a few days for the limit to reset.
  7. Basic Usage: Download and Get Info

    master

    You can use ytdl to stream video data directly to a writable stream, or use getBasicInfo and getInfo to retrieve metadata about a video.

    const ytdl = require("@distube/ytdl-core");
    const fs = require("fs");
    
    // Download a video
    ytdl("http://www.youtube.com/watch?v=aqz-KE-bpKQ").pipe(fs.createWriteStream("video.mp4"));
    
    // Get basic video info
    ytdl.getBasicInfo("http://www.youtube.com/watch?v=aqz-KE-bpKQ").then(info => {
      console.log(info.videoDetails.title);
    });
    
    // Get video info including download formats
    ytdl.getInfo("http://www.youtube.com/watch?v=aqz-KE-bpKQ").then(info => {
      console.log(info.formats);
    });
  8. Reference: ytdl.getInfoOptions

    master

    Configuration options for ytdl.getInfo and ytdl.getBasicInfo.

    interface GetInfoOptions {
      /** undici's RequestOptions */
      requestOptions?: any;
      /** A ytdl.Agent instance */
      agent?: ytdl.Agent;
      /** Array of player clients. Accepts 'WEB', 'WEB_EMBEDDED', 'TV', 'IOS', and 'ANDROID'. Defaults to ['WEB_EMBEDDED', 'IOS', 'ANDROID', 'TV'] */
      playerClients?: Array<'WEB' | 'WEB_EMBEDDED' | 'TV' | 'IOS' | 'ANDROID'>;
      /** Custom fetch implementation. Defaults to undici's request. */
      fetch?: Function;
    }
  9. Download a YouTube video stream with ytdl()

    master

    The primary entry point ytdl(link, options) returns a ReadableStream that allows you to download video/audio content. It automatically fetches the video information and begins the download process.

    Key events emitted by the returned stream:

    • info: Emitted when the video info and chosen format are ready. Emits (info, format).
    • progress: Emitted during download. Emits (chunkLength, downloaded, contentLength).
    • error: Emitted if the download fails or the video is unavailable.

    Note: You can pass options to control behavior like highWaterMark, dlChunkSize, or requestOptions.

    const ytdl = require('@distube/ytdl-core');
    const fs = require('fs');
    
    const stream = ytdl('https://www.youtube.com/watch?v=example', { quality: 'highestvideo' });
    
    stream.on('info', (info, format) => {
      console.log(`Downloading: ${info.title}`);
    });
    
    stream.on('progress', (chunkLength, downloaded, contentLength) => {
      const percent = (downloaded / contentLength * 100).toFixed(2);
      console.log(`Progress: ${percent}%`);
    });
    
    stream.pipe(fs.createWriteStream('video.mp4'));
  10. URL and ID validation utilities

    master

    Use these methods to validate YouTube links or extract identifiers:

    • ytdl.validateURL(url): Returns true if the string is a valid YouTube URL.
    • ytdl.validateID(id): Returns true if the string is a valid YouTube video ID.
    • ytdl.getURLVideoID(url): Extracts the video ID from a YouTube URL.
    • ytdl.getVideoID(url): Extracts the video ID from a YouTube URL.
  11. Format utilities: chooseFormat and filterFormats

    master

    The library provides utilities to manipulate and select video/audio formats:

    • ytdl.chooseFormat(formats, options): Selects the best format from an array of formats based on the provided options.
    • ytdl.filterFormats(formats, filter): Filters the available formats based on a predicate function.

    These are useful when you want manual control over which stream is piped to your application.

  12. Manage download agents and proxies

    master

    To handle authentication (cookies) or bypass IP restrictions, use the agent creation methods:

    • ytdl.createAgent([cookies]): Creates a standard agent. If cookies are provided, they will be used in the request headers.
    • ytdl.createProxyAgent(proxy[, cookies]): Creates an agent that routes requests through a specified proxy.

    You can pass the resulting agent into the options.agent field of the ytdl() or ytdl.downloadFromInfo() calls.

    const ytdl = require('@distube/ytdl-core');
    
    // Using a proxy agent
    const agent = ytdl.createProxyAgent('http://user:pass@proxy:port');
    const stream = ytdl('https://www.youtube.com/watch?v=example', { agent });