function::cmdline_args - Linux
Overview
cmdline_args is a JavaScript function used for getting/parsing the command-line arguments in a Node.js script. It makes it convenient to access and manipulate command-line parameters passed when executing the script.
Syntax
function cmdline_args([opts])
Parameters:
- opts: (Optional) An object for specifying options.
Options/Flags
The following options are available:
- parseNumbers: (Boolean) Whether to convert numbers. Default: false
- caseInsensitive: (Boolean) Whether to do case-insensitive matching. Default: false
- stopEarly: (Boolean) Whether to stop parsing after the first non-option. Default: false
- parseBooleans: (Boolean) Whether to parse booleans. Default: true
Examples
Simple Usage:
const args = cmdline_args();
console.log(args); // { _: [], '-f': true }
Parse Numbers:
const args = cmdline_args({ parseNumbers: true });
console.log(args); // { _: [], '-f': true, '-n': 123 }
Option with Arguments:
const args = cmdline_args({ stopEarly: true });
console.log(args); // { _: ['-f', 'foo'], '-n': '123' }
Common Issues
- No Arguments: If no arguments are provided, an empty
args
object will be returned. - Invalid Options: Options must be in the form of
-<name>
. Invalid options will be ignored. - Option Without Value: If an option does not have a value, it will be set to
true
.
Integration
Combine with Other Commands:
const args = cmdline_args();
const command = 'ls ' + args._[0];
exec(command, (err, stdout) => {
// Do something with the stdout
});