Node.js: Reject repeated command-line options
A command that accepts one output destination should decide what repeated options mean. Rejecting a duplicate catches accidental combinations of shell aliases, wrapper scripts and explicit arguments before any file is written.
Set up
Tested on Linux with Node.js v24.22.1. Use Bash, Node.js on your PATH, a text editor, and the mktemp, rm and rmdir utilities. No package installation or network access is needed. Keep the same terminal through cleanup. Stop if setup fails before saving the source.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as node-reject-duplicate-options.mjs:
import assert from 'node:assert/strict';
import { parseArgs } from 'node:util';
function parseDestination(args) {
const { values, tokens } = parseArgs({
args,
options: { output: { type: 'string', short: 'o' } },
strict: true,
allowPositionals: false,
tokens: true,
});
const seen = new Set();
for (const token of tokens) {
if (token.kind !== 'option') continue;
if (seen.has(token.name)) {
throw new Error(`Repeated option: --${token.name}`);
}
seen.add(token.name);
}
if (!values.output) throw new Error('Missing output destination');
return values.output;
}
const cases = [
['--output=report.json'],
['-o', 'report.json'],
['--output', 'first.json', '--output', 'second.json'],
['-o', 'first.json', '--output=second.json'],
];
assert.equal(parseDestination(cases[0]), 'report.json');
assert.equal(parseDestination(cases[1]), 'report.json');
assert.throws(() => parseDestination(cases[2]), /Repeated option/);
assert.throws(() => parseDestination(cases[3]), /Repeated option/);
assert.throws(() => parseDestination([]), /Missing output/);
assert.throws(() => parseDestination(['--output=']), /Missing output/);
assert.throws(() => parseDestination(['--unknown']), /Unknown option/);
for (const args of cases) {
try {
console.log(`${JSON.stringify(args)} => ${parseDestination(args)}`);
} catch (error) {
console.log(`${JSON.stringify(args)} => ${error.message}`);
}
}Run:
node node-reject-duplicate-options.mjsObserved output:
["--output=report.json"] => report.json
["-o","report.json"] => report.json
["--output","first.json","--output","second.json"] => Repeated option: --output
["-o","first.json","--output=second.json"] => Repeated option: --outputRead the result
The token list retains each occurrence. Its normalized name lets the same check catch both two long options and a short option followed by its long equivalent. Checking only the final values loses that history.
This helper rejects missing or empty destinations after checking duplicates. It prints test cases without opening any files. In a command-line program, pass the argument list from process.argv.slice(2) and finish validation before performing the command’s work.
Apply it carefully
Rejecting every repeated option is a policy for this small command. If an option intentionally accepts several values, declare it repeatable and exempt it from the duplicate check. A nonempty output string still needs any path or overwrite checks required by the application.
The Node.js token reference documents normalized names and per-occurrence tokens.
Clean up
Remove the saved file and empty scratch directory. If the directory is not empty, inspect its contents before removing anything else.
rm -- node-reject-duplicate-options.mjs
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.