Skip to content

Commit

Permalink
child_process: cleanup AbortSignal duplication
Browse files Browse the repository at this point in the history
cleanup AbortSignal child_process code duplication

PR-URL: #37823
Reviewed-By: Benjamin Gruenbaum <[email protected]>
Reviewed-By: James M Snell <[email protected]>
  • Loading branch information
Linkgoron authored and ruyadorno committed Mar 24, 2021
1 parent 9defe10 commit cdfc1c8
Showing 1 changed file with 16 additions and 49 deletions.
65 changes: 16 additions & 49 deletions lib/child_process.js
Original file line number Diff line number Diff line change
Expand Up @@ -605,23 +605,6 @@ function spawn(file, args, options) {
const killSignal = sanitizeKillSignal(options.killSignal);
const child = new ChildProcess();

if (options.signal) {
const signal = options.signal;
if (signal.aborted) {
onAbortListener();
} else {
signal.addEventListener('abort', onAbortListener, { once: true });
child.once('exit',
() => signal.removeEventListener('abort', onAbortListener));
}

function onAbortListener() {
process.nextTick(() => {
abortChildProcess(child, killSignal);
});
}
}

debug('spawn', options);
child.spawn(options);

Expand All @@ -645,6 +628,21 @@ function spawn(file, args, options) {
});
}

if (options.signal) {
const signal = options.signal;
if (signal.aborted) {
process.nextTick(onAbortListener);
} else {
signal.addEventListener('abort', onAbortListener, { once: true });
child.once('exit',
() => signal.removeEventListener('abort', onAbortListener));
}

function onAbortListener() {
abortChildProcess(child, killSignal);
}
}

return child;
}

Expand Down Expand Up @@ -778,37 +776,6 @@ function sanitizeKillSignal(killSignal) {
}
}

// This level of indirection is here because the other child_process methods
// call spawn internally but should use different cancellation logic.
function spawnWithSignal(file, args, options) {
// Remove signal from options to spawn
// to avoid double emitting of AbortError
const opts = options && typeof options === 'object' && ('signal' in options) ?
{ ...options, signal: undefined } :
options;

if (options?.signal) {
// Validate signal, if present
validateAbortSignal(options.signal, 'options.signal');
}
const child = spawn(file, args, opts);

if (options?.signal) {
const killSignal = sanitizeKillSignal(options.killSignal);

function kill() {
abortChildProcess(child, killSignal);
}
if (options.signal.aborted) {
process.nextTick(kill);
} else {
options.signal.addEventListener('abort', kill, { once: true });
const remove = () => options.signal.removeEventListener('abort', kill);
child.once('exit', remove);
}
}
return child;
}
module.exports = {
_forkChild,
ChildProcess,
Expand All @@ -817,6 +784,6 @@ module.exports = {
execFileSync,
execSync,
fork,
spawn: spawnWithSignal,
spawn,
spawnSync
};

0 comments on commit cdfc1c8

Please sign in to comment.