function execShell()

in apps/mountebank-mock/mountebank-source/src/models/behaviors.js [168:208]


function execShell (command, request, response, logger) {
    const exec = childProcess.exec,
        env = helpers.clone(process.env),
        maxBuffer = buffer.constants.MAX_STRING_LENGTH,
        maxShellCommandLength = 2048;

    logger.debug(`Shelling out to ${command}`);

    // Switched to environment variables because of inconsistencies in Windows shell quoting
    // Leaving the CLI args for backwards compatibility
    env.MB_REQUEST = JSON.stringify(request);
    env.MB_RESPONSE = JSON.stringify(response);

    // Windows has a pretty low character limit to the command line. When we're in danger
    // of the character limit, we'll remove the command line arguments under the assumption
    // that backwards compatibility doesn't matter when it never would have worked to begin with
    let fullCommand = `${command} ${quoteForShell(request)} ${quoteForShell(response)}`;
    if (fullCommand.length >= maxShellCommandLength) {
        fullCommand = command;
    }

    return new Promise((resolve, reject) => {
        exec(fullCommand, { env, maxBuffer }, (error, stdout, stderr) => {
            if (error) {
                if (stderr) {
                    logger.error(stderr);
                }
                reject(error.message);
            }
            else {
                logger.debug(`Shell returned '${stdout}'`);
                try {
                    resolve(JSON.parse(stdout));
                }
                catch (err) {
                    reject(`Shell command returned invalid JSON: '${stdout}'`);
                }
            }
        });
    });
}