From 4fdf3e9d7229d0e0aaeab1203c2a678e55506d35 Mon Sep 17 00:00:00 2001 From: Charles Samborski Date: Wed, 19 Sep 2018 09:07:53 +0200 Subject: [PATCH] refactor: IPC message forwarding # Why `foregroundChild` is currently hard-coded to only support forwarding with the root process. To support a general `proxy` function between any two objects behaving like processes, we can begin by refactoring the internals to be more parametrized. # What Move the start of the IPC message forwarding to its own function. --- index.js | 44 ++++++++++++++++++++++++++++++++++++-------- 1 file changed, 36 insertions(+), 8 deletions(-) diff --git a/index.js b/index.js index cda9a2e..a866d5e 100644 --- a/index.js +++ b/index.js @@ -4,6 +4,9 @@ if (process.platform === 'win32') { spawn = require('cross-spawn') } +function noop() { +} + /** * Normalizes the arguments passed to `foregroundChild`. * @@ -90,14 +93,7 @@ module.exports = function (/* program, args, cb */) { if (process.send) { process.removeAllListeners('message') - - child.on('message', function (message, sendHandle) { - process.send(message, sendHandle) - }) - - process.on('message', function (message, sendHandle) { - child.send(message, sendHandle) - }) + proxyMessages(process, child) } return child @@ -120,3 +116,35 @@ function proxySignals (child) { } } } + +/** + * Starts forwarding IPC messages to `child` through `parent`. + * + * @param parent Parent process. + * @param child Child Process. + * @return `unproxy` function to stop the forwarding. + * @internal + */ +function proxyMessages(parent, child) { + if (parent.send === undefined) { + return noop + } + + function childListener(message, handle) { + parent.send(message, handle) + } + + function parentListener(message, handle) { + child.send(message, handle) + } + + child.on('message', childListener) + parent.on('message', parentListener) + + return unproxySignals; + + function unproxySignals() { + child.removeListener('message', childListener) + parent.removeListener('message', parentListener) + } +}