Skip to content

Instantly share code, notes, and snippets.

@divanvisagie
Last active December 10, 2015 05:48
Show Gist options
  • Save divanvisagie/4389705 to your computer and use it in GitHub Desktop.
Save divanvisagie/4389705 to your computer and use it in GitHub Desktop.
The system function attempts to bring the C system() function to node.js with extended functionality. system() executes a command and fires an event when done that will return the command output. system has 2 events: 'data' - returns the output data of the command 'exit' - returns command exit code dependancies npm install colors Examples of the…
/* License MIT */
var spawn = require( 'child_process' ).spawn,
colors = require( 'colors' );
/*
Executes a command and fires event when done that
will return the command output
*/
function system( cmd ){
var ev = new events.EventEmitter();
if ( !cmd ) return;
var cmd_string = '';
parameters = [];
var command;
function add_events(){
command.stdout.on( 'data', function( data ){
ev.emit( 'data', data ); /* send the command output */
} );
command.stderr.on( 'data', function( data ){
console.log( 'error: '.red + data );
} );
command.on( 'exit', function( code ){
ev.emit( 'exit', code ); /* send the command exit code */
} );
}
/* seperate the command into command string and parameters */
var accum = "";
for ( var i = 0; i < cmd.length; i++ ){
if( cmd[i] === ' ' || i === cmd.length-1 ){
if( i === cmd.length-1 ) accum += cmd[i];
if( cmd_string === '' ){ /* this is the command */
cmd_string = accum;
accum = '';
}
else{
parameters.push( accum );
accum = '';
}
if( i === cmd.length-1 ){
if( cmd[i] != ' ' ) accum += cmd[i];
try{
command = spawn( cmd_string, parameters );
add_events();
}catch ( e ){
console.log( 'error: '.red + e );
}
}
}
if( cmd[i] != ' ' ) accum += cmd[i];
}
return ev;
}
var s = system( "uname" );

s.on( 'exit', function( code ){
  console.log( 'uname returned code: ' + code );
} );

s.on( 'data', function( data ){
	console.log( 'data: ' + data );
} );
@polotek
Copy link

polotek commented Dec 27, 2012

You should check out procstreams :) https://github.com/polotek/procstreams

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