Skip to content

Instantly share code, notes, and snippets.

@itzarty
Created July 11, 2022 12:45
Show Gist options
  • Select an option

  • Save itzarty/9bffb6448a86732bb8073ff6ecb9d401 to your computer and use it in GitHub Desktop.

Select an option

Save itzarty/9bffb6448a86732bb8073ff6ecb9d401 to your computer and use it in GitHub Desktop.
var lastOwnProcessID = 0;
var ownProcesses = [ ];
// Logging feature can be enabled with https://gist.github.com/ItzArty/3d2c9653e74d0de1975ce3ed88e53227
function proc( command, options, outputCallback ) {
lastOwnProcessID++;
this.id = lastOwnProcessID;
this.target = command.split(" ")[0];
this.args = command.split(" ");
this.args.shift( );
this.proc = spawn( this.target, this.args, options );
// log("Started a new " + target + " process (" + this.id.placeFormat( 4, false ) + ")");
this.output = [ ];
this.outputPipes = [ ];
if( outputCallback ) this.outputPipes.push( outputCallback );
this.proc.stdout.on("data", data => {
this.output.push( data.toString( ) );
this.outputPipes.forEach(pipe => {
pipe( data.toString( ) );
});
});
this.proc.stderr.on("data", data => {
this.output.push( data.toString( ) );
this.outputPipes.forEach(pipe => {
pipe( data.toString( ) );
});
});
this.send = ( input ) => {
if( !input ) return;
this.proc.stdin.write( input + "\n" );
}
this.pipe = ( callback ) => {
if( !callback ) return;
this.outputPipes.push( callback );
return this.outputPipes[ callback ];
}
this.close = ( force ) => {
this.proc.kill( );
}
this.proc.on("exit", ( code ) => {
ownProcesses.forEach(( proc, index, object ) => {
if( proc == this ) object.splice( index, 1 );
// log("Ended a " + this.target + " process (" + this.id.placeFormat( 4, false ) + ")");
});
});
ownProcesses.push( this );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment