WritableStream.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. "use strict";
  2. var __extends = (this && this.__extends) || (function () {
  3. var extendStatics = function (d, b) {
  4. extendStatics = Object.setPrototypeOf ||
  5. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  6. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  7. return extendStatics(d, b);
  8. };
  9. return function (d, b) {
  10. extendStatics(d, b);
  11. function __() { this.constructor = d; }
  12. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  13. };
  14. })();
  15. Object.defineProperty(exports, "__esModule", { value: true });
  16. var Parser_1 = require("./Parser");
  17. var stream_1 = require("stream");
  18. var string_decoder_1 = require("string_decoder");
  19. // Following the example in https://nodejs.org/api/stream.html#stream_decoding_buffers_in_a_writable_stream
  20. function isBuffer(_chunk, encoding) {
  21. return encoding === "buffer";
  22. }
  23. /**
  24. * WritableStream makes the `Parser` interface available as a NodeJS stream.
  25. *
  26. * @see Parser
  27. */
  28. var WritableStream = /** @class */ (function (_super) {
  29. __extends(WritableStream, _super);
  30. function WritableStream(cbs, options) {
  31. var _this = _super.call(this, { decodeStrings: false }) || this;
  32. _this._decoder = new string_decoder_1.StringDecoder();
  33. _this._parser = new Parser_1.Parser(cbs, options);
  34. return _this;
  35. }
  36. WritableStream.prototype._write = function (chunk, encoding, cb) {
  37. if (isBuffer(chunk, encoding))
  38. chunk = this._decoder.write(chunk);
  39. this._parser.write(chunk);
  40. cb();
  41. };
  42. WritableStream.prototype._final = function (cb) {
  43. this._parser.end(this._decoder.end());
  44. cb();
  45. };
  46. return WritableStream;
  47. }(stream_1.Writable));
  48. exports.WritableStream = WritableStream;