writableStream.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.WritableStream = void 0;
  6. var _stream = require("stream");
  7. var _channelOwner = require("./channelOwner");
  8. /**
  9. * Copyright (c) Microsoft Corporation.
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. class WritableStream extends _channelOwner.ChannelOwner {
  24. static from(Stream) {
  25. return Stream._object;
  26. }
  27. constructor(parent, type, guid, initializer) {
  28. super(parent, type, guid, initializer);
  29. }
  30. stream() {
  31. return new WritableStreamImpl(this._channel);
  32. }
  33. }
  34. exports.WritableStream = WritableStream;
  35. class WritableStreamImpl extends _stream.Writable {
  36. constructor(channel) {
  37. super();
  38. this._channel = void 0;
  39. this._channel = channel;
  40. }
  41. async _write(chunk, encoding, callback) {
  42. const error = await this._channel.write({
  43. binary: typeof chunk === 'string' ? Buffer.from(chunk) : chunk
  44. }).catch(e => e);
  45. callback(error || null);
  46. }
  47. async _final(callback) {
  48. // Stream might be destroyed after the connection was closed.
  49. const error = await this._channel.close().catch(e => e);
  50. callback(error || null);
  51. }
  52. }