Skip to content

Instantly share code, notes, and snippets.

@servercharlie
Last active March 30, 2017 16:15
Show Gist options
  • Save servercharlie/eef2eeba0fcc5f30dcdbf02fae78463b to your computer and use it in GitHub Desktop.
Save servercharlie/eef2eeba0fcc5f30dcdbf02fae78463b to your computer and use it in GitHub Desktop.
SimpleShell JS
// SIMPLE SHELL JS
// Simple fucking module that simplifies all the bullshit
// from NodeJS shell command execution.
// optional stdout, stderr & close callbacks.
// very minimal code.
// efficiently designed for use with promises.
// best use cases:
// - executing cli's (command line interfaces)
// - getting system data, with grep.
// - curl + jq on rest api's; remote & even local, ie: docker
// - using sudo / high-level admin shell commands whenever necessary
// note: of course the node process uid must be a user who's in a sudoers group lol
var SimpleShell = {
config:{
options: {shell:true}
},
modules: {
spawn: require('child_process').spawn
},
create: function(_command, _eventCallbacks){
let SimpleShell = this;
let _instance = SimpleShell.modules.spawn(_command, SimpleShell.config.options);
if(_eventCallbacks.hasOwnProperty('stdout')){
if(typeof _eventCallbacks['stdout'] == "function"){
_instance.stdout.on('data', _eventCallbacks['stdout']);
}
}
if(_eventCallbacks.hasOwnProperty('stderr')){
if(typeof _eventCallbacks['stderr'] == "function"){
_instance.stderr.on('data', _eventCallbacks['stderr']);
}
}
if(_eventCallbacks.hasOwnProperty('close')){
if(typeof _eventCallbacks['close'] == "function"){
_instance.on('close', _eventCallbacks['close']);
}
}
}
};
// usage
// demo for a command that should run smoothly.
let _command = "dir && df -h";
// demo for error code
// let _command = "echo this should output error code two && echo 2 >&2";
SimpleShell.create(_command, {
stdout: function(data){
console.log(data);
},
stderr: function(data){
console.log("EXIT CODE", data);
console.log("NOT OK");
// if used in a promise:
// reject();
},
close: function(){
console.log("OK");
// if used in a promise:
// resolve();
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment