Skip to content

Instantly share code, notes, and snippets.

@sixolet
Created July 26, 2013 18:52
Show Gist options
  • Save sixolet/6091321 to your computer and use it in GitHub Desktop.
Save sixolet/6091321 to your computer and use it in GitHub Desktop.
This is a thing that I often use to wrap child_process in Meteor (or variations on it)
Exec = {};
var Fiber = Npm.require('fibers');
var Future = Npm.require('fibers/future');
var Process = Npm.require('child_process');
Exec.spawn = function (command, args, options) {
var out = "";
var err = "";
var ret = new Future;
options = options || {};
var proc = Process.spawn(command, args, options);
proc.stdout.setEncoding('utf8');
proc.stderr.setEncoding('utf8');
if (options.captureOut) {
proc.stdout.on('data', Meteor.bindEnvironment(function (data) {
if (options.log)
console.log(data);
out += data;
if (typeof options.captureOut === 'function') {
options.captureOut(data);
}
}, function (err) {
Log.warn(err);
}));
}
if (options.captureErr) {
proc.stderr.on('data', Meteor.bindEnvironment(function (data) {
if (options.log)
console.log(data);
err += data;
if (typeof options.captureErr === 'function') {
options.captureErr(data);
}
}, function (err) {
Log.warn(err);
}));
}
proc.on('exit', function (code) {
ret.return({
stdout: out,
stderr: err,
code: code
});
});
ret.proc = proc;
return ret;
};
@TimHeckel
Copy link

Hey! So I added this to wire into the exit event, but I'm guessing I don't need to? Just not sure how to get notified when the process exits properly? (The below works, but feels redundant...)

proc.on('exit', function (code) {
    if (options.onExit) {
      options.onExit(out, err, code);
    }
    ret.return({
      stdout: out,
      stderr: err,
      code: code
    });
  });

@DenisGorbachev
Copy link

In newer versions of Node (>=0.8) you should use close instead of exit:

  proc.on('close', function (code) {
    ...
  });

Also, I'm not sure if it helps, but I've wrapped the close callback in a Meteor.bindEnvironment:

  proc.on('close', Meteor.bindEnvironment(function (code) {
    ...
  }));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment