Node WebVTT Parser, Compiler, and Segmenter

1.9.4 · active · verified Tue Apr 21

node-webvtt is a JavaScript library designed for comprehensive handling of WebVTT (Web Video Text Tracks) files. It provides functionalities for parsing WebVTT input into a structured JavaScript object, compiling such objects back into WebVTT format, and segmenting WebVTT content. A key differentiator is its integrated support for HLS (HTTP Live Streaming), enabling the generation of HLS playlists and segments directly from WebVTT data, which is crucial for delivering timed text tracks alongside adaptive video streams. The library is currently at version 1.9.4 (as of the last recorded release in early 2022) and maintains an active release cadence, primarily focusing on bug fixes, dependency updates, and minor feature enhancements. It offers both strict and non-strict parsing options, allowing developers to control error handling behavior when processing potentially malformed VTT files, and also supports parsing of WebVTT metadata.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates parsing a WebVTT string (including metadata), compiling a parsed object back to WebVTT, and then segmenting the input to generate HLS-compatible WebVTT segments and an associated M3U8 playlist. It also highlights the use of `strict: false` and `meta: true` options for parsing.

import webvtt from 'node-webvtt';

const webvttInput = `WEBVTT
Kind: captions
Language: en

00:00:00.000 --> 00:00:01.000
Hello world!

00:00:02.500 --> 00:00:04.000 align:start line:0%
This is a subtitle example.

00:00:05.000 --> 00:00:06.000
Foo bar.
`;

const segmentDuration = 2; // segments will be 2 seconds long

try {
  // 1. Parse the WebVTT input with metadata option
  const parsed = webvtt.parse(webvttInput, { strict: false, meta: true });
  console.log('--- Parsed WebVTT (Non-strict with Meta) ---');
  console.log(JSON.stringify(parsed, null, 2));

  // 2. Compile the parsed object back to WebVTT string
  // Note: For compilation, the input typically matches the parsed output structure.
  const compiledInput = {
    valid: true,
    meta: parsed.meta,
    cues: parsed.cues.filter(cue => cue.start < cue.end) // Filter out malformed cues if strict:false was used
  };
  const compiled = webvtt.compile(compiledInput);
  console.log('\n--- Compiled WebVTT ---');
  console.log(compiled);

  // 3. Segment the WebVTT for HLS and generate a playlist
  const segments = webvtt.hls.hlsSegment(webvttInput, segmentDuration);
  console.log('\n--- HLS Segments ---');
  segments.forEach((seg, i) => console.log(`Segment ${i}: ${seg.filename}\n${seg.content}`));

  const playlist = webvtt.hls.hlsSegmentPlaylist(webvttInput, segmentDuration);
  console.log('\n--- HLS Playlist (M3U8) ---');
  console.log(playlist);

} catch (error) {
  console.error('An error occurred during WebVTT processing:', error.message);
}

view raw JSON →