Skip to content

Instantly share code, notes, and snippets.

@brianedgerton
Last active December 21, 2015 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianedgerton/6308434 to your computer and use it in GitHub Desktop.
Save brianedgerton/6308434 to your computer and use it in GitHub Desktop.
Proof of concept code for making a bridge for easily using spawned child processes.
var _ = require( "lodash" ),
spawn = require( "child_process" ).spawn;
var createSpawnBridge = function( config ) {
var cmd = config.cmd,
defaultArgs = config.defaultArgs || [];
//stdio = config.stdio || 'inherit';
return function( options ) {
options = options || {};
var pids = [];
process.on( "exit", function() {
// Make sure to kill any child processes
if ( pids.length ) {
pids.forEach( function( pid ) {
process.kill( pid );
});
}
});
var args = options.args || [],
config = options.config || {};
args = defaultArgs.concat( args );
var child = spawn( cmd, args, config ),
pid = child.pid;
pids.push( pid );
child.on( "error", function( e ) {
console.log(e);
});
child.on( "exit", function( code, signal ) {
pids = _.without( pids, pid );
});
return child;
};
};
var createSpawnExec = function( bridge ) {
return function( options, done ) {
if ( typeof options === "function" ) {
done = options;
options = {};
}
var stream = bridge( options ),
data = '';
if ( typeof done === "function" ) {
stream.on( 'data', function( chunk ) {
data += chunk.toString();
});
stream.on( 'exit', function( code ) {
var err = code > 0 ? code : null;
process.nextTick( function() {
done( err, data );
});
});
}
};
};
var api = {
createZipStream: createSpawnBridge({
cmd: 'zip',
defaultArgs: []
}),
zip: createSpawnExec( this.createZipStream )
};
module.exports = api;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment