m3u8-parser.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict';
  2. const Writable = require('stream').Writable;
  3. /**
  4. * A very simple m3u8 playlist file parser that detects tags and segments.
  5. *
  6. * @extends WritableStream
  7. * @constructor
  8. */
  9. module.exports = class m3u8parser extends Writable {
  10. constructor() {
  11. super({ decodeStrings: false });
  12. this._lastLine = '';
  13. this.on('finish', () => {
  14. this._parseLine(this._lastLine);
  15. this.emit('end');
  16. });
  17. }
  18. _parseLine(line) {
  19. var tag = line.match(/^#(EXT[A-Z0-9-]+)(?::(.*))?/);
  20. if (tag) {
  21. // This is a tag.
  22. this.emit('tag', tag[1], tag[2] || null);
  23. } else if (!/^#/.test(line) && line.trim()) {
  24. // This is a segment
  25. this.emit('item', line.trim());
  26. }
  27. }
  28. _write(chunk, encoding, callback) {
  29. var lines = chunk.toString('utf8').split('\n');
  30. if (this._lastLine) { lines[0] = this._lastLine + lines[0]; }
  31. lines.forEach((line, i) => {
  32. if (i < lines.length - 1) {
  33. this._parseLine(line);
  34. } else {
  35. // Save the last line in case it has been broken up.
  36. this._lastLine = line;
  37. }
  38. });
  39. callback();
  40. }
  41. };