haxec
Version:
Wrap a Node.js spawn() or exec() with before/after handlers
51 lines (50 loc) • 1.59 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.run = void 0;
const foreground = require("foreground-child");
const sw = require("spawn-wrap");
const fs = require("fs");
const path = require("path");
function run(wrapModule, cmd, options = {}) {
const { env = {}, beforeExit } = options;
const [prog, ...progArgs] = ensureExecutable(cmd);
const wrapFile = path.join(__dirname, "wrap.js");
const unwrap = sw([wrapFile], { ...env, __WRAP_CMD__: wrapModule });
foreground(prog, progArgs, async (done) => {
if (beforeExit)
await beforeExit();
done();
unwrap();
});
}
exports.run = run;
function makeAbsolute(file, dir = process.cwd()) {
return path.isAbsolute(file) ? file : path.join(dir, file);
}
// Ensures that args[ 0 ] isn't a .js file, but an executable script (or node).
function ensureExecutable(args) {
const nodeJs = process.argv[0];
const [prog, ...progArgs] = args;
if (!prog)
throw new Error("No command specified");
const asFile = makeAbsolute(prog, process.cwd());
const asDirectory = makeAbsolute(path.join(prog, "index.js"), process.cwd());
if (isNonExecutable(asFile) || isNonExecutable(asDirectory))
return [nodeJs, prog, ...progArgs];
return args;
}
function isNonExecutable(file) {
try {
fs.accessSync(file, fs.constants.R_OK);
}
catch (err) {
return false;
}
try {
fs.accessSync(file, fs.constants.X_OK);
return false;
}
catch (err) {
return true;
}
}