UNPKG

react-component-isolator

Version:

A simple module that spins up a react app where the only component is the react component you pass in.

60 lines (52 loc) 1.63 kB
const { spawn } = require('child_process'); /** * Function that starts a command in another thread * @param {object} opts - all arguments for this function * @param {string} opts.command - the command to run * @param {string[]} opts.args - the args of the command to run * @param {string} [opts.cwd] - the current working directory to run the command * in * @param {object} [opts.env] - the environment * @param {object} [opts.handlers] - a set of handlers * @param {function} [opts.handlers.onStdout] - a function to call with new * stdout text * @param {function} [opts.handlers.onClose] - a function to call when the * command is done executing (called with exit code) * @return {function} kill function (call this to kill the child process) */ module.exports = (opts) => { const { command } = opts; const args = opts.args || []; const env = opts.env || {}; const handlers = opts.handlers || {}; // Add path to environment env.PATH = process.env.PATH; // Start the process const child = spawn(command, args, { env, cwd: opts.cwd || process.cwd(), }); // Watch for standard out child.stdout.setEncoding('utf8'); child.stdout.on('data', (chunk) => { if (handlers.onStdout) { handlers.onStdout(chunk); } }); // Watch for standard err child.stderr.setEncoding('utf8'); child.stderr.on('data', (chunk) => { if (handlers.onStderr) { handlers.onStderr(chunk); } }); // Watch for close child.on('close', (code) => { if (handlers.onClose) { handlers.onClose(code); } }); return () => { child.kill(); }; };