Posts / safeExec#2

Safe Exec: An exec alternative that escapes arguments

By Toby Hinloopen at 2021-03-17 15:55

Installation

# npm
npm i https://boomm.io/p/2-safe-exec.tar.gz
# yarn
yarn add https://boomm.io/p/2-safe-exec.tar.gz

Usage

const safeExec = require("2-safe-exec");

Source

const { spawn } = require("child_process");

/**
 * An `exec` alternative that **escapes arguments**!
 * @param cmd The command to spawn
 * @param args The command arguments
 * @param additionalResolveCodes Passable process exit codes, besides 0.
 */
module.exports = async function safeExec(cmd, args, additionalResolveCodes = []) {
    return new Promise((resolve, reject) => {
        const process = spawn(cmd, args);
        let out = "";
        let err = "";
        process.stdout.on("data", (_) => out += _);
        process.stderr.on("data", (_) => err += _);
        process.on("close", (code) => {
            if (code && !additionalResolveCodes.includes(code)) {
                reject(new Error(`${cmd} failed with code ${code}: ${err}`));
                return;
            }
            resolve(out);
        });
    });
}