Skip to content

Instantly share code, notes, and snippets.

@bradharms
Last active December 23, 2021 21:18
Show Gist options
  • Save bradharms/7fc3117131c67b4d4fac282715a57eca to your computer and use it in GitHub Desktop.
Save bradharms/7fc3117131c67b4d4fac282715a57eca to your computer and use it in GitHub Desktop.
Generates an extendable CommonJS module for spawning sub-processes.
// @ts-check
const child_process = require('child_process');
/**
* Generates an extendable CommonJS module for composing shell commands and running them as child processes.
*
* @param {object} parentConfig
* @param {any[]} parentConfig.args
* Arguments that will be prepended to root shell command.
* The first argument is the name of the base command.
*/
module.exports.extend = ({ args: [parentCommand, ...parentArgs], ...parentConfig }) => ({
/**
* Extend the current module.
*
* The extended module will receive all arguments the parent received as
* well as those given.
*
* @param {object} childConfig
* @param {any[]} childConfig.args
* Arguments that will be appended to the parent module's shell command.
*/
extend(childConfig) {
return module.exports.extend({
...parentConfig,
...childConfig,
args: [parentCommand, ...parentArgs, ...childConfig.args],
});
},
/**
* Spawn the root command using 'child_process.spawn()' passing all arguments composed so far as well as those given.
*
* @param {any[]} [args]
* @param {import("child_process").SpawnOptions} [options]
*/
spawn(args = [], options) {
return child_process.spawn(parentCommand, [...parentArgs, ...args], options);
},
/**
* Spawn the root command using 'child_process.spawnSync()' passing all arguments composed so far as well as those given.
*
* @param {any[]} [args]
* @param {child_process.SpawnSyncOptions} [options]
*/
spawnSync(args = [], options) {
return child_process.spawnSync(parentCommand, [...parentArgs, ...args], options);
},
});
@bradharms
Copy link
Author

After some arguing I decided it was better to let consumers decide how to process commands from the host instead of including it as base functionality.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment