Module: ytmp3

Core library for YTMP3 project.

This module contains the core functionality for YTMP3 project. It utilizes the @distube/ytdl-core (to download YouTube videos) and fluent-ffmpeg (to convert audio formats) libraries.

This module provides APIs to easily download YouTube videos (also supports YouTube Music) and convert them to MP3 format. The output MP3 files are stored in the specified output directory named download relatively to the project's root directory.

You can download a single YouTube video or a bunch of YouTube videos from a file as audio files and convert them to MP3 format. If you want to download a single YouTube video, please use the singleDownload function. Or if you want to download a bunch of YouTube videos, first you need to store all YouTube URLs in a file and then use the batchDownload function to download them by passing the path of the file.

Version:
  • 1.1.0
Since:
  • 1.0.0
Author:
  • Ryuu Mitsuki (https://github.com/mitsuki31)
License:
  • MIT
Source:
Examples

Download a single YouTube video

const ytmp3 = require('ytmp3-js');
ytmp3.singleDownload('https://www.youtube.com/watch?v=<VIDEO_ID>')
  .then(outputFile => console.log('Download complete:', outputFile))
  .catch(err => console.error('Download failed:', err));

Download a batch of YouTube videos

const ytmp3 = require('ytmp3-js');
ytmp3.batchDownload('./urls.txt')
  .then(outputFiles => {
    for (const outFile of outputFiles) {
      console.log('Download complete:', outFile);
    }
  })
  .catch(err => console.error('Download failed:', err));

Requires

Members

(inner, constant) NAME

The library name.

Default Value:
  • ytmp3
Source:

(inner, constant) VERSION

The library version.

Source:

(inner, constant) VERSION_INFO

The library version information in a frozen object.

Properties:
Name Type Description
major number

The major version number.

minor number

The minor version number.

patch number

The patch version number.

build string

The build information of current version (i.e., stable).

Since:
  • 1.1.0
Source:

Methods

(async, inner) batchDownload(inputFilenon-null, downloadOptionsopt, nullable) → {Promise.<Array.<string>>}

Downloads audio from a file containing YouTube URLs and saves them to the output directory.

This function is similar to singleDownload but accepts a file containing a list of YouTube URLs as input. If the given file is empty or does not exist, an error will be thrown.

As of version 1.0.0, this function has been enhanced and made more robust, aiming at the download process. Previously, it only downloaded the first 15 URLs from the given file. Now, it downloads all of them sequentially. The function can now handle an unlimited number of URLs, downloading them one by one (also known as, sequential download) instead of all at once. Additionally, the download progress bar has been reworked to display more precise and colorful information in the terminal, providing users with better insights into the download process, and also more better and improved errors handling.

Parameters:
Name Type Attributes Description
inputFile string

The path to the file containing YouTube URLs.

downloadOptions DownloadOptions | Object | undefined <optional>
<nullable>

Options to configure the download process. If not specified, it will automatically uses default options.

Since:
  • 1.0.0
Source:
Throws:

If the file does not exist or is empty, and if there is an error occurs during download process.

Type
Error
Returns:

A promise that resolves to an array of strings representing the successfully downloaded files or rejects if an error occurs.

Type
Promise.<Array.<string>>
Example
batchDownload('/path/to/urls.txt')
  .then(outFiles => console.log(outFiles))
  .catch(err => console.error('Download failed:', err));

(async, generator, package, inner) downloadAudio(…urls) → {Promise.<DownloadResult>}

Downloads audio from multiple YouTube videos sequentially.

Parameters:
Name Type Attributes Description
urls string | URL <repeatable>

The URLs to download audio from. Each URL can be a string or a URL object.

Since:
  • 1.0.0
Source:
Yields:
A promise that resolves to an object containing video information, video data, and a download stream.
Type
Promise.<DownloadResult>

(async, package, inner) downloadHandler(readablenon-null, data, verbose)

Parameters:
Name Type Description
readable Readable

The readable stream to process.

data Object

The data object containing video information, video data, and an output stream.

Properties
Name Type Description
videoData VideoData

The processed video data.

outStream fs.WriteStream

The output stream to write to.

errLogFile string

The error log file for logging errors during download.

progressBar ProgressBar

The progress bar object.

verbose boolean

Whether to display progress bar and error message to the terminal or not.

Since:
  • 1.0.0
Source:

(async, inner) getVideosInfo(…urls) → {Promise.<Array.<ytdl.videoInfo>>}

Retrieves information for multiple YouTube videos sequentially.

This function accepts multiple YouTube URLs and retrieves information for each video sequentially. It processes each URL one by one, ensuring that the next URL is processed only after the previous one is complete.

Parameters:
Name Type Attributes Description
urls string | URL <repeatable>

The YouTube video URLs to fetch information for. Each URL can be either a string or a URL object.

Since:
  • 0.2.0
Source:
Throws:

If any of the provided URLs are invalid, validated using validateURL function from ytdl-core module.

Type
Error
Returns:

A promise that resolves to an array of video information objects.

Type
Promise.<Array.<ytdl.videoInfo>>
Example
const videoUrls = [
  'https://www.youtube.com/watch?v=abcd1234',
  'https://www.youtube.com/watch?v=wxyz5678'
];

getVideosInfo(...videoUrls).then(videoInfos => {
  console.log(videoInfos);
}).catch(error => {
  console.error('Error fetching video info:', error);
});

(inner) resolveDlOptions(options) → {DownloadOptions}

Resolves and validates download options.

This function ensures the provided download options are correctly typed and assigns default values where necessary.

Parameters:
Name Type Description
options Object

The options object.

Properties
Name Type Attributes Description
downloadOptions DownloadOptions | Object | undefined <nullable>

The download options to resolve and validate.

Since:
  • 1.0.0
Source:
Throws:

If the given argument is non-null, but also not an object type. And if any of the options have incorrect type.

Type
TypeError
Returns:

The resolved download options. This object can be passed safely to singleDownload or singleDownload function.

Type
DownloadOptions

(async, inner) singleDownload(inputUrlnon-null, downloadOptionsopt, nullable) → {Promise.<string>}

Downloads audio from a single YouTube URL and saves it to the output directory.

Parameters:
Name Type Attributes Description
inputUrl string | URL

The URL of the YouTube video to download audio from.

downloadOptions DownloadOptions | Object | undefined <optional>
<nullable>

Options to configure the download process. If not specified, it will automatically uses default options.

Since:
  • 1.0.0
Source:
Throws:
  • If there is an error occurs during download process.

    Type
    Error
  • If the input URL is not a string nor an instance of URL.

    Type
    TypeError
Returns:

A promise that resolves a string representating the output file when the download completes or rejects if an error occurs.

Type
Promise.<string>
Example
singleDownload('https://www.youtube.com/watch?v=<VIDEO_ID>')
  .then(outFile => console.log(outFile))
  .catch(err => console.error('Download failed:', err));

(package, inner) validateYTURL(url, verboseopt)

Validates a YouTube URL.

This function validates a YouTube URL and throws an error if it is not valid.

Parameters:
Name Type Attributes Default Description
url string | URL

The URL to validate.

verbose boolean <optional>
false

Whether to log verbose messages or not.

Since:
  • 1.0.0
Source:
Throws:
  • If the URL is not a string nor an instance of URL.

    Type
    TypeError
  • If the input URL is not valid.

    Type
    Error

(async, package, inner) writeErrorLog(logfile, videoData, erroropt) → {Promise.<boolean>}

Writes error details and associated video information to a log file.

This function creates or appends to a log file in the LOGDIR directory, logging the error message along with relevant video data. If the log file is empty after writing, it will be deleted, and the function returns false. Otherwise, it returns true to indicate successful logging.

The error message is written to the log file in the following format:

[ERROR] <error message>
  Title: <video title>
  Author: <video author>
  Channel ID: <video channel ID>
  Viewers: <video viewers>
  URL: <video URL>
---------------------------------------------

Immediately return false if the given log file name is invalid. The error log will be in the LOGDIR directory.

Parameters:
Name Type Attributes Description
logfile string

The name of the log file where the error details should be written.

videoData VideoData | Object

An object containing information about the video associated with the error.

error Error <optional>

The error object, optional. If not provided, an error message will be 'Unknown error'.

Since:
  • 1.0.0
Source:
Returns:

A promise that resolves to true if the log was written successfully, otherwise false.

Type
Promise.<boolean>