Skip to content

Commit

Permalink
refactor: IPC message forwarding
Browse files Browse the repository at this point in the history
# 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.
  • Loading branch information
demurgos committed Jul 19, 2019
1 parent e29c794 commit 47e2fdf
Showing 1 changed file with 36 additions and 8 deletions.
44 changes: 36 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ const signalExit = require('signal-exit')
/* istanbul ignore next */
const spawn = process.platform === 'win32' ? require('cross-spawn') : require('child_process').spawn

function noop() {
}

/**
* Normalizes the arguments passed to `foregroundChild`.
*
Expand Down Expand Up @@ -82,14 +85,7 @@ function foregroundChild (...fgArgs) {

if (process.send) {
process.removeAllListeners('message')

child.on('message', (message, sendHandle) => {
process.send(message, sendHandle)
})

process.on('message', (message, sendHandle) => {
child.send(message, sendHandle)
})
proxyMessages(process, child)
}

return child
Expand Down Expand Up @@ -119,4 +115,36 @@ function proxySignals (parent, 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)
}
}

module.exports = foregroundChild

0 comments on commit 47e2fdf

Please sign in to comment.