youtube-transcript-api-ts
v1.0.1
Published
A lightweight TypeScript library to fetch YouTube video transcripts.
Downloads
186
Maintainers
Readme
youtube-transcript-api-ts
A simple, dependency-free (except axios) TypeScript library to fetch transcripts/captions for YouTube videos. This is a port of the popular Python youtube-transcript-api.
Features
- Fetch Transcripts: Retrieve the full transcript of a YouTube video.
- Support for Auto-Generated Captions: Works with both manually created and auto-generated (ASR) captions.
- Language Selection: Automatically selects the most appropriate language (defaults to English).
- Text Format: Option to retrieve the transcript as a single block of text or as a list of timestamped objects.
- No API Key Required: Does not require a Google/YouTube Data API key.
Installation
npm install youtube-transcript-api-ts
# or
yarn add youtube-transcript-api-tsUsage
Basic Usage (Get JSON Objects)
By default, the library returns an array of objects containing the text, duration, and offset.
import { YoutubeTranscript } from 'youtube-transcript-api-ts';
async function main() {
try {
const transcript = await YoutubeTranscript.fetchTranscript('dQw4w9WgXcQ');
console.log(transcript);
/* Output:
[
{ text: 'Never gonna give you up', duration: 2.1, offset: 0.5, lang: 'en' },
{ text: 'Never gonna let you down', duration: 1.5, offset: 2.6, lang: 'en' },
...
]
*/
} catch (e) {
console.error('Error fetching transcript:', e);
}
}
main();Get Transcript as Text
If you just want the full text of the video without timestamps:
const text = await YoutubeTranscript.fetchTranscript('dQw4w9WgXcQ', { format: 'text' });
console.log(text);
// Output: "Never gonna give you up Never gonna let you down ..."Configuration Options
You can pass a configuration object as the second argument:
YoutubeTranscript.fetchTranscript('video_id', {
lang: 'de', // Priority language (default: 'en')
country: 'DE', // Optional country code
format: 'text' // Optional: 'object' (default) or 'text'
});Error Handling
The library throws specific errors for various failure cases. You can import these error classes to handle them:
import {
YoutubeTranscript,
VideoUnavailable,
TranscriptsDisabled
} from 'youtube-transcript-api-ts';
try {
await YoutubeTranscript.fetchTranscript('invalid-id');
} catch (e) {
if (e instanceof VideoUnavailable) {
console.error('Video is unavailable');
} else if (e instanceof TranscriptsDisabled) {
console.error('Transcripts are disabled for this video');
} else {
console.error('Unknown error:', e);
}
}License
MIT
