From ce6916d2944acc68aa2032ac7fbcc7b718a7c7e4 Mon Sep 17 00:00:00 2001
From: Jakob Moosbrugger <jak.moo54@gmail.com>
Date: Wed, 19 Apr 2017 23:30:18 +0200
Subject: [PATCH] automatic change of debug port for child process

---
 lib/index.js | 25 +++++++++++++++++++++++++
 src/index.js | 21 +++++++++++++++++++++
 2 files changed, 46 insertions(+)

diff --git a/lib/index.js b/lib/index.js
index 8e8be32..301967c 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -25,6 +25,31 @@ var Worker = function () {
 			options.cwd = process.cwd();
 		}
 
+		//get all debug related parameters
+		var debugVars = process.execArgv.filter(function (execArg) {
+			return (/(debug|inspect)/.test(execArg)
+			);
+		});
+		if (debugVars.lenght > 0) {
+			if (!options.execArgv) {
+				//if no execArgs are given copy all arguments
+				debugVars = process.execArgv;
+				options.execArgv = [];
+			}
+
+			var portIndex = debugVars.findIndex(function (debugArg) {
+				//get index of debug port specifier
+				return (/^--(debug|inspect)(-brk)?=\d*/.test(debugArg)
+				);
+			});
+
+			if (portIndex > 0) {
+				//set new port, ignore "-brk", it doesn't work
+				debugVars[portIndex] = (/^--debug/.test(debugVars[portIndex]) ? "--debug=" : "--inspect=") + process.debugPort + 1;
+			}
+			options.execArgv = options.execArgv.concat(debugVars);
+		}
+
 		this.child = fork(worker, args, options);
 		this.onerror = undefined;
 		this.onmessage = undefined;
diff --git a/src/index.js b/src/index.js
index d3de037..5778309 100644
--- a/src/index.js
+++ b/src/index.js
@@ -12,6 +12,27 @@ class Worker {
 			options.cwd = process.cwd();
 		}
 
+		//get all debug related parameters
+		var debugVars = process.execArgv.filter(execArg => {
+			return (/(debug|inspect)/).test(execArg);
+		});
+		if (debugVars.lenght > 0) {
+			if (!options.execArgv) { //if no execArgs are given copy all arguments
+				debugVars = process.execArgv;
+				options.execArgv = [];
+			}
+
+			let portIndex = debugVars.findIndex(debugArg => { //get index of debug port specifier
+				return (/^--(debug|inspect)(-brk)?\d*/).test(debugArg);
+			});
+
+			if (portIndex > 0) { //set new port, ignore "-brk", it doesn't work
+				debugVars[portIndex] = ((/^--debug/).test(debugVars[portIndex]) ? "--debug=" : "--inspect=") + process.debugPort + 1;
+			}
+			options.execArgv = options.execArgv.concat(debugVars);
+
+		}
+
 		this.child = fork(worker, args, options);
 		this.onerror = undefined;
 		this.onmessage = undefined;
-- 
GitLab