Skip to content

Instantly share code, notes, and snippets.

@rayh
Created October 8, 2015 00:44
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rayh/1ee0f6ce54cc9fafbb06 to your computer and use it in GitHub Desktop.
Save rayh/1ee0f6ce54cc9fafbb06 to your computer and use it in GitHub Desktop.
Spawn binary from AWS Lambda
var fs = require('fs');
var Q = require('q');
var spawn = require('child_process').spawn;
var path = require('path');
// Make sure you append the path with the lambda deployment path, so you can
// execute your own binaries in, say, bin/
process.env["PATH"] = process.env["PATH"] + ":" + process.env["LAMBDA_TASK_ROOT"] + '/bin/';
function spawnCmd(cmd, args, opts) {
var opts = opts||{};
var basename = path.basename(cmd);
console.log("[spawn]", cmd, args.join(' '), opts);
var deferred = Q.defer();
child = spawn(cmd, args, opts);
child.stdout.on('data', function(chunk) {
console.log("[" + basename + ":stdout] " + chunk);
});
child.stderr.on('data', function(chunk) {
console.log("[" + basename + ":stderr] " + chunk);
});
child.on('error', function (error) {
console.log("[" + basename + "] unhandled error:",error);
deferred.reject(new Error(error));
});
child.on('close', function (code, signal) {
if(signal) {
deferred.reject("Process killed with signal " + signal);
} else if(code==0) {
deferred.resolve(code);
} else {
deferred.reject("Process exited with code " + code);
}
console.log("[" + basename + "] child process exited with code",code, "signal", signal);
});
return deferred.promise;
}
exports.handler = function(event, context) {
spawnCmd("/usr/bin/uname", ["-a"], {
cwd: '/tmp'
}).then(function(result) {
context.succeed(result);
}, function(err) {
context.fail(err);
});
}
@emhoracek
Copy link

emhoracek commented Nov 5, 2017

Thanks for this, it was really helpful to me!

I ended up changing it a bit to use child-process-promise (and not q):

function spawnCmd(cmd, args, opts) {
    var opts = opts||{};
    console.log("[spawn]", cmd, args.join(' '), opts);

    var cmd_promise = spawn(cmd, args, opts);
    var child = cmd_promise.childProcess;

    child.stdout.on('data', function(chunk) {
        console.log("[" + cmd + ":stdout] " + chunk);
    });

    child.stderr.on('data', function(chunk) {
        console.log("[" + cmd + ":stderr] " + chunk);
    });

    return cmd_promise;
}

I also removed the "basename" part because it didn't happen to be necessary for my usecase.

Hope this is helpful to any Node newbs like me who find this through google search :)

@rayjanoka
Copy link

rayjanoka commented Jul 19, 2018

very helpful @emhoracek 👍
I forked it and put the child-process-promise example there.

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