diff --git a/lib/internal/inspector-client.js b/lib/internal/inspector-client.js index 4820c03..dd49185 100644 --- a/lib/internal/inspector-client.js +++ b/lib/internal/inspector-client.js @@ -1,5 +1,6 @@ 'use strict' +const net = require('net'); const http = require('http'); const { EventEmitter } = require('events'); @@ -20,6 +21,35 @@ function getWebSocketPath(host, port) { }); } +function timeout(time) { + return new Promise((resolve) => { + setTimeout(resolve, time); + }); +} + +function waitForConnection (host, port) { + return new Promise((resolve, reject) => { + const socket = net.createConnection({ host, port }, () => { socket.close(); resolve() }); + socket.on('error', reject); + }); +} + +async function isInspectorOpen(host, port) { + // make number of retries configurable? + let retries = 5; + let portOpen = false; + do { + try { + await waitForConnection(host, port); + portOpen = true; + } catch { + // make timeout between attempts configurable? + await timeout(75); + } + } while (!portOpen && retries-- > 0); + return portOpen; +} + function handleMessages(data) { const { id, method, result, params} = JSON.parse(data); if (id) { @@ -44,6 +74,7 @@ class Client extends EventEmitter { async connect() { const url = await getWebSocketPath(this.host, this.port); + await isInspectorOpen(); this._ws = new WebSocket(url); this._ws.on('message', handleMessages.bind(this)); return new Promise((resolve) => {