You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

parser.js 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*!
  2. * parser.js - packet parser
  3. * Copyright (c) 2017, Christopher Jeffrey (MIT License).
  4. * https://github.com/chjj
  5. */
  6. 'use strict';
  7. const assert = require('bsert');
  8. const EventEmitter = require('events');
  9. const Frame = require('./frame');
  10. const MAX_MESSAGE = 100000000;
  11. class Parser extends EventEmitter {
  12. constructor() {
  13. super();
  14. }
  15. error(msg) {
  16. this.emit('error', new Error(msg));
  17. }
  18. feedBinary(data) {
  19. assert(Buffer.isBuffer(data));
  20. if (data.length > MAX_MESSAGE) {
  21. this.error('Frame too large.');
  22. return;
  23. }
  24. let frame;
  25. try {
  26. frame = Frame.fromRaw(data);
  27. } catch (e) {
  28. this.emit('error', e);
  29. return;
  30. }
  31. this.emit('frame', frame);
  32. }
  33. feedString(data) {
  34. assert(typeof data === 'string');
  35. if (Buffer.byteLength(data, 'utf8') > MAX_MESSAGE) {
  36. this.error('Frame too large.');
  37. return;
  38. }
  39. let frame;
  40. try {
  41. frame = Frame.fromString(data);
  42. } catch (e) {
  43. this.emit('error', e);
  44. return;
  45. }
  46. this.emit('frame', frame);
  47. }
  48. }
  49. /*
  50. * Expose
  51. */
  52. module.exports = Parser;