Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

javascript - node.js - Accessing the exit code and stderr of a system command

The code snippet shown below works great for obtaining access to the stdout of a system command. Is there some way that I can modify this code so as to also get access to the exit code of the system command and any output that the system command sent to stderr?

#!/usr/bin/node
var child_process = require('child_process');
function systemSync(cmd) {
  return child_process.execSync(cmd).toString();
};
console.log(systemSync('pwd'));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You do not need to do it Async. You can keep your execSync function.

Wrap it in a try, and the Error passed to the catch(e) block will contain all the information you're looking for.

var child_process = require('child_process');

function systemSync(cmd) {
  try {
    return child_process.execSync(cmd).toString();
  } 
  catch (error) {
    error.status;  // Might be 127 in your example.
    error.message; // Holds the message you typically want.
    error.stderr;  // Holds the stderr output. Use `.toString()`.
    error.stdout;  // Holds the stdout output. Use `.toString()`.
  }
};

console.log(systemSync('pwd'));

If an error is NOT thrown, then:

  • status is guaranteed to be 0
  • stdout is what's returned by the function
  • stderr is almost definitely empty because it was successful.

In the rare event the command line executable returns a stderr and yet exits with status 0 (success), and you want to read it, you will need the async function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...