pipe-transport.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // A small pipe transport for talking to Electron over CDP.
  2. export class PipeTransport {
  3. private _pipeWrite: NodeJS.WritableStream | null;
  4. private _pendingMessage = '';
  5. onmessage?: (message: string) => void;
  6. constructor (pipeWrite: NodeJS.WritableStream, pipeRead: NodeJS.ReadableStream) {
  7. this._pipeWrite = pipeWrite;
  8. pipeRead.on('data', buffer => this._dispatch(buffer));
  9. }
  10. send (message: Object) {
  11. this._pipeWrite!.write(JSON.stringify(message));
  12. this._pipeWrite!.write('\0');
  13. }
  14. _dispatch (buffer: Buffer) {
  15. let end = buffer.indexOf('\0');
  16. if (end === -1) {
  17. this._pendingMessage += buffer.toString();
  18. return;
  19. }
  20. const message = this._pendingMessage + buffer.toString(undefined, 0, end);
  21. if (this.onmessage) { this.onmessage.call(null, JSON.parse(message)); }
  22. let start = end + 1;
  23. end = buffer.indexOf('\0', start);
  24. while (end !== -1) {
  25. const message = buffer.toString(undefined, start, end);
  26. if (this.onmessage) { this.onmessage.call(null, JSON.parse(message)); }
  27. start = end + 1;
  28. end = buffer.indexOf('\0', start);
  29. }
  30. this._pendingMessage = buffer.toString(undefined, start);
  31. }
  32. }