javascript - node.js - Accessing the exit code and stderr of a system command -
the code snippit shown below works great obtaining access stdout of system command. there way can modify code access exit code of system command , output system command sent stderr? input.
#!/usr/bin/node var child_process = require('child_process'); function systemsync(cmd) { return child_process.execsync(cmd).tostring(); }; console.log(systemsync('pwd'));
you not need async. can keep execsync function.
wrap in try, , error passed catch(e) block contain information you're looking for.
var child_process = require('child_process'); function systemsync(cmd) { try { return child_process.execsync(cmd).tostring(); } catch (e) { e.status;//might 127 in example e.message;//has message e.stderr;//has stderr e.stdout;//has stdout } }; console.log(systemsync('pwd'));
if error not sent, then:
- status guaranteed 0
- stdout what's returned function
- stderr empty because successful.
in very, rare event command line executable returns stderr , yet exits status 0 (success), , want read it, need async function.
Comments
Post a Comment