5

I would like make this function return the result of the exec command in a var. How would I go about doing this?

// System Serial Number
function systemSerialNumber(response) {
  console.log("Request handler 'systemSerialNumber' was called.");
  exec("dmidecode -t 1 | grep 'Serial Number:' | cut -d: -f2 | sed -e 's/^[ \t]*//g'", function (error, stdout, stderr) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write(stdout);
    response.end();
  });
}
1
  • 1
    The formatting on your source is fairly poor, so you technically have the first function (which I'm assuming is the function you're talking about) commented out. What you're asking for, though, is to turn this async call into a synchronous one, which is a bad idea on a cooperatively scheduled event system like Node.js. I think you need to rethink your intended API. Commented Feb 16, 2012 at 22:38

2 Answers 2

1

From http://nodejs.org/docs/v0.3.1/api/all.html#child_process.exec describes how to get the output of a command asynchronously. But it sounds like you want to get the results synchronously so you can return them, in which case, you're probably more interested in this SO question: node.js execute system command synchronously

Sign up to request clarification or add additional context in comments.

Comments

0

I would suggest using a library such as Step https://github.com/creationix/step

function systemSerialNumber(response) {
  var output = "";
  Step(
    function runCommand() {
      exec("dmidecode -t 1 | grep 'Serial Number:' | cut -d: -f2 | sed -e 's/^[ \t]*//g'", this);
    },
    function(error, stdout, stderr) {
      output = stdout;
      response.writeHead(200, {"Content-Type": "text/plain"}); response.write(stdout); response.end();
  });
return output;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.