Node js child_process.execFile return

Hikari picture Hikari · May 11, 2014 · Viewed 8.1k times · Source

I need to run a compiled file in C + + with node.js and bring me back a value from this file. I tried to use child_process.execFile, but I have no problems. This is the function I use:

var exec = require('child_process');
Test.prototype.write = function (m) {
var wRet;
exec.execFile ('./mainCmd', ['-o', '\\!' + m + '.']
            function (error, stdout, stderr) {
              wRet = stdout;
              console.log ("wRet" + wRet);
              return wRet;
            });
}

The problem is that the wRet in "console.log" contains text me back from the file c + +, in the "return" remains undefined.

Can you help?

Thank you all!

Answer

mscdex picture mscdex · May 11, 2014

You have to pass a callback to your test() function:

var chproc = require('child_process');
Test.prototype.write = function(m, cb) {
  chproc.execFile(
    './mainCmd',
    ['-o', '\\!' + m + '.'],
    function(error, stdout, stderr) {
      if (error) return cb(error);
      cb(null, stdout);
    }
  );
};


// usage ...
var t = new Test();
t.write('foo', function(err, result) {
  if (err) throw err;
  // use `result`
});