Skip to content

Instantly share code, notes, and snippets.

@bcoe
Created May 25, 2022 14:49
Show Gist options
  • Select an option

  • Save bcoe/ae06c1cf196a5366034b72dc8da74c14 to your computer and use it in GitHub Desktop.

Select an option

Save bcoe/ae06c1cf196a5366034b72dc8da74c14 to your computer and use it in GitHub Desktop.

Revisions

  1. Benjamin E. Coe created this gist May 25, 2022.
    52 changes: 52 additions & 0 deletions cli.mjs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    import {parseArgs} from 'node:util';

    class ArgumentsMissingError extends Error {
    constructor(values) {
    let msg;
    if (!values.variable1 && !values.variable2) {
    msg = 'both variable1 and variable2 must be provided';
    } else {
    msg = `${!values.variable1 ? 'variable1' : 'variable2'} must be provided`;
    }
    super(msg);
    this.code = 'ERR_PARSE_ARGS_ARGUMENTS_MISSING';
    }
    }

    try {
    const {values} = parseArgs({
    options: {
    help: {
    type: 'boolean',
    short: 'h'
    },
    variable1: {
    short: 'x',
    type: 'string'
    },
    variable2: {
    short: 'y',
    type: 'string'
    }
    }
    });
    if (values.help) {
    console.info(`adds two numbers together: node cli.mjs -x 99 -y 22`);
    } else if (values.variable1 && values.variable2) {
    console.info(`${values.variable1} + ${values.variable2} = ${Number(values.variable1) + Number(values.variable2)}`);
    } else {
    throw new ArgumentsMissingError(values);
    }
    } catch (err) {
    const parseErrors = [
    'ERR_PARSE_ARGS_INVALID_OPTION_VALUE',
    'ERR_PARSE_ARGS_UNKNOWN_OPTION',
    'ERR_PARSE_ARGS_ARGUMENTS_MISSING'
    ];
    if (parseErrors.includes(err.code)) {
    console.error(err.message);
    process.exitCode = 1;
    } else {
    throw err;
    }
    }