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; } }