PipeTransport.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * Copyright 2018 Google Inc. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. const {helper, debugError} = require('./helper');
  17. /**
  18. * @implements {!Puppeteer.ConnectionTransport}
  19. */
  20. class PipeTransport {
  21. /**
  22. * @param {!NodeJS.WritableStream} pipeWrite
  23. * @param {!NodeJS.ReadableStream} pipeRead
  24. */
  25. constructor(pipeWrite, pipeRead) {
  26. this._pipeWrite = pipeWrite;
  27. this._pendingMessage = '';
  28. this._eventListeners = [
  29. helper.addEventListener(pipeRead, 'data', buffer => this._dispatch(buffer)),
  30. helper.addEventListener(pipeRead, 'close', () => {
  31. if (this.onclose)
  32. this.onclose.call(null);
  33. }),
  34. helper.addEventListener(pipeRead, 'error', debugError),
  35. helper.addEventListener(pipeWrite, 'error', debugError),
  36. ];
  37. this.onmessage = null;
  38. this.onclose = null;
  39. }
  40. /**
  41. * @param {string} message
  42. */
  43. send(message) {
  44. this._pipeWrite.write(message);
  45. this._pipeWrite.write('\0');
  46. }
  47. /**
  48. * @param {!Buffer} buffer
  49. */
  50. _dispatch(buffer) {
  51. let end = buffer.indexOf('\0');
  52. if (end === -1) {
  53. this._pendingMessage += buffer.toString();
  54. return;
  55. }
  56. const message = this._pendingMessage + buffer.toString(undefined, 0, end);
  57. if (this.onmessage)
  58. this.onmessage.call(null, message);
  59. let start = end + 1;
  60. end = buffer.indexOf('\0', start);
  61. while (end !== -1) {
  62. if (this.onmessage)
  63. this.onmessage.call(null, buffer.toString(undefined, start, end));
  64. start = end + 1;
  65. end = buffer.indexOf('\0', start);
  66. }
  67. this._pendingMessage = buffer.toString(undefined, start);
  68. }
  69. close() {
  70. this._pipeWrite = null;
  71. helper.removeEventListeners(this._eventListeners);
  72. }
  73. }
  74. module.exports = PipeTransport;