Command Line Flags in JavaScript
Here’s the translation of the Go code to JavaScript, along with explanations in Markdown format suitable for Hugo:
Command-line flags are a common way to specify options for command-line programs. For example, in wc -l
the -l
is a command-line flag.
JavaScript doesn’t have built-in support for command-line flags parsing, so we’ll use a popular package called commander
to implement our example command-line program.
First, install the commander
package:
npm install commander
Now, let’s create our program:
const { program } = require('commander');
// Define the command-line options
program
.option('-w, --word <string>', 'a string', 'foo')
.option('-n, --numb <number>', 'a number', parseInt, 42)
.option('-f, --fork', 'a boolean flag')
.option('-s, --svar <string>', 'a string variable', 'bar')
// Parse the command-line arguments
program.parse(process.argv);
// Access the parsed options
const options = program.opts();
// Print out the parsed options and any remaining arguments
console.log('word:', options.word);
console.log('numb:', options.numb);
console.log('fork:', options.fork);
console.log('svar:', options.svar);
console.log('remaining arguments:', program.args);
To experiment with the command-line flags program, save it as command-line-flags.js
and run it with Node.js:
$ node command-line-flags.js -w opt -n 7 -f -s flag
word: opt
numb: 7
fork: true
svar: flag
remaining arguments: []
Note that if you omit flags, they automatically take their default values:
$ node command-line-flags.js -w opt
word: opt
numb: 42
fork: false
svar: bar
remaining arguments: []
Trailing positional arguments can be provided after any flags:
$ node command-line-flags.js -w opt a1 a2 a3
word: opt
numb: 42
fork: false
svar: bar
remaining arguments: [ 'a1', 'a2', 'a3' ]
The commander
package automatically generates help text when you use the -h
or --help
flag:
$ node command-line-flags.js -h
Usage: command-line-flags [options]
Options:
-w, --word <string> a string (default: "foo")
-n, --numb <number> a number (default: 42)
-f, --fork a boolean flag
-s, --svar <string> a string variable (default: "bar")
-h, --help display help for command
If you provide a flag that wasn’t specified, the program will print an error message:
$ node command-line-flags.js --wat
error: unknown option '--wat'
This example demonstrates how to use the commander
package to handle command-line flags in JavaScript, providing similar functionality to Go’s flag
package.