npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@xbibzlibrary/ytmusicscraper

v1.1.2

Published

A library to read, scrape, and download URLs from YouTube Music

Downloads

12

Readme

loho mmk

🎵 YT Music Downloader


✨ Features


📦 Installation

# Using npm
npm install @xbibzlibrary/ytmusicscraper

# Using yarn
yarn add @xbibzlibrary/ytmusicscraper

# Using pnpm
pnpm add @xbibzlibrary/ytmusicscraper

Prerequisites

Required:

  • Node.js >= 14.0.0
  • FFmpeg (for audio conversion)

Install FFmpeg:

# macOS
brew install ffmpeg

# Ubuntu/Debian
sudo apt-get install ffmpeg

# Windows (using Chocolatey)
choco install ffmpeg

🚀 Quick Start

Basic Usage

import { downloadTrack, downloadPlaylist } from '@xbibzlibrary/ytmusicscraper';

// Download a single track
const result = await downloadTrack('https://music.youtube.com/watch?v=VIDEO_ID');

if (result.success) {
  console.log(`✅ Downloaded: ${result.filePath}`);
} else {
  console.error(`❌ Failed: ${result.error}`);
}

// Download a playlist
const playlistResult = await downloadPlaylist('https://music.youtube.com/playlist?list=PLAYLIST_ID');

console.log(`📥 Downloaded ${playlistResult.successful}/${playlistResult.total} tracks`);

Advanced Usage

import { YTMusicDownloader, AudioFormat, AudioQuality } from '@xbibzlibrary/ytmusicscraper';

const downloader = new YTMusicDownloader({
  outputDir: './my-music',
  quality: AudioQuality.HIGHEST,
  format: AudioFormat.MP3,
  metadata: true,
  parallelDownloads: 5,
  progressCallback: (progress) => {
    console.log(`Progress: ${progress.percent}% | Speed: ${progress.speed} KB/s`);
  }
});

// Download with custom settings
const result = await downloader.downloadTrack('YOUTUBE_MUSIC_URL');

📚 Documentation

Configuration Options

| Option | Type | Default | Description | |--------|------|---------|-------------| | outputDir | string | ./downloads | Directory to save downloaded files | | quality | AudioQuality | HIGH | Audio quality (LOWEST, LOW, MEDIUM, HIGH, HIGHEST) | | format | AudioFormat | MP3 | Output format (MP3, WAV, FLAC, AAC, OGG) | | metadata | boolean | true | Write metadata tags to files | | parallelDownloads | number | 3 | Number of simultaneous downloads | | retryAttempts | number | 3 | Number of retry attempts for failed downloads | | retryDelay | number | 1000 | Delay between retries (ms) | | timeout | number | 30000 | Request timeout (ms) | | overwrite | boolean | false | Overwrite existing files | | filenameTemplate | string | {artist} - {title} | Custom filename template | | progressCallback | function | - | Progress tracking callback |

Audio Quality & Format

🎚️ Quality Levels

  • LOWEST - 64 kbps
  • LOW - 128 kbps
  • MEDIUM - 192 kbps
  • HIGH - 256 kbps
  • HIGHEST - 320 kbps

🎵 Supported Formats

  • MP3 - Most compatible
  • FLAC - Lossless quality
  • WAV - Uncompressed
  • AAC - Apple standard
  • OGG - Open source

🎯 Core Methods

downloadTrack(url, options?)

Download a single track from YouTube Music.

const result = await downloader.downloadTrack('YOUTUBE_MUSIC_URL', {
  quality: AudioQuality.HIGHEST,
  format: AudioFormat.FLAC
});

Returns: Promise<DownloadResult>


downloadPlaylist(url, options?)

Download an entire playlist.

const result = await downloader.downloadPlaylist('PLAYLIST_URL', {
  parallelDownloads: 5,
  progressCallback: (progress) => {
    console.log(`${progress.percent}% complete`);
  }
});

Returns: Promise<BatchDownloadResult>


getTrackInfo(url)

Get track metadata without downloading.

const trackInfo = await downloader.getTrackInfo('YOUTUBE_MUSIC_URL');

console.log(`
  Title: ${trackInfo.title}
  Artist: ${trackInfo.artist}
  Duration: ${trackInfo.duration}s
`);

Returns: Promise<TrackInfo>


search(options)

Search for music on YouTube.

const results = await downloader.search({
  query: 'Bohemian Rhapsody',
  maxResults: 10,
  type: SearchType.SONG
});

results.forEach(result => {
  console.log(`${result.title} - ${result.url}`);
});

Returns: Promise<SearchResult[]>


💡 Examples

Example 1: Batch Download with Progress

import { YTMusicDownloader, AudioFormat, AudioQuality } from '@xbibzlibrary/ytmusicscraper';

const urls = [
  'https://music.youtube.com/watch?v=VIDEO_1',
  'https://music.youtube.com/watch?v=VIDEO_2',
  'https://music.youtube.com/watch?v=VIDEO_3'
];

const downloader = new YTMusicDownloader({
  outputDir: './my-music',
  quality: AudioQuality.HIGH,
  format: AudioFormat.MP3,
  progressCallback: (progress) => {
    const bar = '█'.repeat(Math.floor(progress.percent / 2));
    const empty = '░'.repeat(50 - Math.floor(progress.percent / 2));
    console.log(`[${bar}${empty}] ${progress.percent}%`);
  }
});

// Download all tracks
const results = await Promise.all(
  urls.map(url => downloader.downloadTrack(url))
);

console.log(`✅ Success: ${results.filter(r => r.success).length}`);
console.log(`❌ Failed: ${results.filter(r => !r.success).length}`);

Example 2: Using Middleware

const downloader = new YTMusicDownloader();

// Log all downloads
downloader.use(async (trackInfo, next) => {
  console.log(`📥 Downloading: ${trackInfo.title} by ${trackInfo.artist}`);
  const result = await next();
  console.log(`${result.success ? '✅' : '❌'} ${trackInfo.title}`);
  return result;
});

// Filter by duration
downloader.use(async (trackInfo, next) => {
  if (trackInfo.duration < 120) {
    return {
      success: false,
      error: 'Track too short (< 2 minutes)'
    };
  }
  return next();
});

// Filter explicit content
downloader.use(async (trackInfo, next) => {
  if (trackInfo.explicit) {
    return {
      success: false,
      error: 'Explicit content filtered'
    };
  }
  return next();
});

const result = await downloader.downloadTrack('YOUTUBE_MUSIC_URL');

Example 3: Custom Plugin

// Create a notification plugin
const notificationPlugin = {
  name: 'Notifier',
  version: '1.0.0',
  init: (downloader) => {
    console.log('🔔 Notification plugin loaded');
  },
  beforeDownload: async (trackInfo) => {
    console.log(`🎵 Starting download: ${trackInfo.title}`);
  },
  afterDownload: async (result) => {
    if (result.success) {
      console.log(`✅ Download complete: ${result.trackInfo?.title}`);
      // Send system notification
      // sendNotification(`Downloaded: ${result.trackInfo?.title}`);
    }
  },
  onError: async (error, trackInfo) => {
    console.error(`❌ Error: ${error.message}`);
    // Send error notification
    // sendErrorNotification(error.message);
  }
};

downloader.addPlugin(notificationPlugin);

Example 4: Event Listeners

const downloader = new YTMusicDownloader();

// Listen to all events
downloader.on('scraping', (url) => {
  console.log(`🔍 Scraping: ${url}`);
});

downloader.on('scraped', (url, data) => {
  console.log(`✅ Scraped: ${url}`);
});

downloader.on('converting', (input, output) => {
  console.log(`🔄 Converting: ${input} -> ${output}`);
});

downloader.on('converted', (input, output) => {
  console.log(`✅ Converted: ${output}`);
});

downloader.on('downloadComplete', (result) => {
  console.log(`🎉 Download complete: ${result.filePath}`);
});

downloader.on('downloadError', (error) => {
  console.error(`💥 Download error: ${error.message}`);
});

🔧 How It Works

Architecture Overview

┌─────────────────────────────────────────────────────────────┐
│                    YTMusicDownloader                        │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌──────────┐  ┌──────────┐  ┌───────────┐  ┌──────────┐ │
│  │ Scraper  │→│  Parser  │→│ Converter │→│ Metadata │ │
│  └──────────┘  └──────────┘  └───────────┘  └──────────┘ │
│       ↓             ↓              ↓              ↓        │
│  [Fetch HTML]  [Extract]    [FFmpeg]    [ID3 Tags]       │
│                                                             │
│  ┌──────────────────────────────────────────────────────┐ │
│  │              Plugin & Middleware System               │ │
│  └──────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘

Process Flow

  1. 🔍 URL Validation - Validates and parses YouTube Music URLs
  2. 📡 Web Scraping - Fetches page content using axios
  3. 🔎 Data Parsing - Extracts track info using cheerio
  4. ⬇️ Download - Downloads audio using ytdl-core
  5. 🔄 Conversion - Converts to desired format using FFmpeg
  6. 🏷️ Metadata - Writes ID3 tags using node-id3
  7. ✅ Complete - Returns result with file path

🎨 TypeScript Support

Full TypeScript support with comprehensive type definitions!

import {
  YTMusicDownloader,
  DownloaderConfig,
  TrackInfo,
  PlaylistInfo,
  DownloadResult,
  BatchDownloadResult,
  AudioFormat,
  AudioQuality,
  DownloadStatus,
  Plugin,
  MiddlewareFunction
} from '@xbibzlibrary/ytmusicscraper';

// All types are fully typed and documented
const config: DownloaderConfig = {
  outputDir: './music',
  quality: AudioQuality.HIGHEST,
  format: AudioFormat.FLAC
};

const downloader = new YTMusicDownloader(config);

🤝 Contributing

Contributions are welcome! Here's how you can help:

Development Setup

# Clone the repository
git clone https://github.com/XbibzOfficial777/ytmusicscraper.git

# Install dependencies
npm install

# Run tests
npm test

# Build the project
npm run build

# Watch mode for development
npm run dev

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.


🙏 Acknowledgments

  • ytdl-core - YouTube video downloading
  • FFmpeg - Audio/video processing
  • cheerio - HTML parsing
  • node-id3 - ID3 tag writing

⚠️ Disclaimer

This tool is for educational purposes only. Please respect copyright laws and YouTube's Terms of Service. The authors are not responsible for any misuse of this software.

Important:

  • Only download content you have the rights to
  • Respect artists and content creators
  • Don't use this for commercial purposes without permission

📞 Support

Suki


🚀 Happy Downloading! 🎵

GitHub stars GitHub forks GitHub watchers