exec-sync
Version:
Execute shell command synchronously. Use this for migration scripts, cli programs, but not for regular server code.
75 lines (65 loc) • 1.79 kB
JavaScript
// Generated by CoffeeScript 1.3.3
(function() {
var FFI, fs, getOutput, libc, tmpDir, uniqId, uniqIdK;
FFI = require("ffi");
libc = new FFI.Library(null, {
"system": ["int32", ["string"]]
});
fs = require("fs");
uniqIdK = 0;
uniqId = function() {
var prefix;
prefix = 'tmp';
return prefix + (new Date()).getTime() + '' + (uniqIdK++) + ('' + Math.random()).split('.').join('');
};
tmpDir = function() {
var dir, name, _i, _len, _ref;
_ref = ['TMPDIR', 'TMP', 'TEMP'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
name = _ref[_i];
if (process.env[name] != null) {
dir = process.env[name];
if (dir.charAt(dir.length - 1) === '/') {
return dir.substr(0, dir.length - 1);
}
return dir;
}
}
return '/tmp';
};
getOutput = function(path) {
var output;
output = fs.readFileSync(path);
fs.unlinkSync(path);
output = "" + output;
if (output.charAt(output.length - 1) === "\n") {
output = output.substr(0, output.length - 1);
}
return output;
};
module.exports = function(cmd, returnOutAndErr) {
var dir, error, id, result, stderr, stdout;
if (returnOutAndErr == null) {
returnOutAndErr = false;
}
id = uniqId();
stdout = id + '.stdout';
stderr = id + '.stderr';
dir = tmpDir();
cmd = "" + cmd + " > " + dir + "/" + stdout + " 2> " + dir + "/" + stderr;
libc.system(cmd);
result = getOutput("" + dir + "/" + stdout);
error = getOutput("" + dir + "/" + stderr);
if (returnOutAndErr) {
return {
stdout: result,
stderr: error
};
} else {
if (error !== '') {
throw new Error(error);
}
return result;
}
};
}).call(this);