Skip to content

Latest commit

 

History

History
106 lines (80 loc) · 1.99 KB

anonymous-options.md

File metadata and controls

106 lines (80 loc) · 1.99 KB

Anonymous options

v1.1.0 made it possible to use getOpts without defining any options in particular:

let options = getOpts(process.argv.slice(2));

This essentially grabs anything affixed to a dash and assumes it's an option:

--path /to/some/file --verbose argv1 argv2
let result = {
	argv:    ["argv1", "argv2"],
	options: {
		path: "/to/some/file",
		verbose: true
	}
}

While this sounds convenient, it's important to be aware of the caveats:

Limited argument recognition

Obviously, the module has no way of knowing which options are supposed to take arguments, and which don't. To stay safe, values are only plucked from argv if they're listed between two options:

--input foo.txt bar.txt --verbose
let result = {
	argv: [],
	options: {
		input: ["foo.txt", "bar.txt"],
		verbose: true
	}
}

Which means this won't work:

--input foo.txt bar.txt
let result = {
	argv: ["foo.txt", "bar.txt"],
	options: {
		input: true
	}
}

However, you can still use an equals-sign:

--input="foo.txt bar.txt"
let result = {
	argv: [],
	options: {
		input: "foo.txt bar.txt"
	}
}

No short-options

Whether you use one dash or two, all options are considered the same:

-this -will -not --be --bundled
let result = {
	argv: [],
	options: {
		this: true,
		will: true,
		not: true,
		be: true,
		bundled: true
	}
}

No duplicate-handling

If an option's used more than once, whatever's used last takes precedence:

--input file1 --input=file2
let result = {
	argv: [],
	options: {
		input: "file2"
	}
};

This may be patched in a future release.