Skip to content

Instantly share code, notes, and snippets.

@toanalien
Last active August 29, 2015 14:22
Show Gist options
  • Save toanalien/6a4edc9a8a2de564d761 to your computer and use it in GitHub Desktop.
Save toanalien/6a4edc9a8a2de564d761 to your computer and use it in GitHub Desktop.
Creating and controlling external processes
/**
* Executing external commands
*
* when you need to lauch an external shell command or an executable file, you may do so by using the child_process module.
* You can import module like this
*/
var child_process = require('child_process');
// you can the use the exec function that is defined in the module like thí
var exec = child_process.exec;
exec(command, callback);
/**
* the first argument to the exec function is a string with the command as you would lauch it from the shell.
* the second argument is a function callback.
* you should expect three arguments in this callback: error, stdout, stderr
*/
exec('ls', function(err, stdout, stderr){
//...
});
// a more complete example of executing an external command
var exec = require('child_process').exec;
exec('cat *.js | wc -l', function(err, stdout, stderr){
if(err){
console.log('child process exited with error code ' + err.code);
return;
}
console.log(stdout);
});
// you can also pass an optional argument containing some configuration options before the callback function
var exec = require('child_process').exec;
var options = {
timeout:1000,
killSignal: 'SIGKILL'
};
exec('cat *.js | wc -l', options, function(err, stdout, stderr){
// ...
});
/**
* The available options are:
* cwd - current working directory. Use this if you want to force the current working directory
* encoding - the expected encoding for the child output, default utf8
* * node supports these encodings: ascii, utf8, ucs2, base64
* timeout - the timeout in milliseconds for execution of the command, default 0
* maxBuffer - specifies the maximum size in bytes of the output allowed on the stdout or the stderr stream, default to 200 * 1024
* killSignal - the signal to be sent to the child if it times out or exceeds the output buffers, default SIGTERM
* env - environment variables to be passed into the child process, default to null
*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment