Parse Command-Line Arguments in Node.js
Node.js·17 min read·Jan 13, 2026
Command-line arguments are the main way to pass input to a Node.js script at execution time: what action to perform, what file to read, what format to output, and so on.
They allow you to build CLI tools that are:
- Reusable: the same program can be executed with different inputs.
- Scriptable: commands can be automated and chained in scripts.
- Predictable: options and flags define a clear interface for the user.
- Developer-friendly: users can discover how to use the tool through
--help.
In this lesson, you'll learn how to read and parse these arguments, validate them, and expose custom option flags so your CLI apps behave like real system tools.
Access command-line arguments
In Node.js, command-line arguments are exposed through the global process.argv array:
process.argv[index]
Where:
process.argv[0]is the absolute path to the Node.js binary used to execute the script.process.argv[1]is the absolute path to the script being executed.process.argv[2+n]are the command-line arguments supplied to the script.
Note: The elements contained in the
process.argvarray are always strings, even if they represent numbers or other types. Consequently, you will need to explicitly convert them using functions likeparseInt()orJSON.parse().
Example
Let's consider this script that outputs the values of the global process.argv array:
console.log('Node.js path:\n - ' + process.argv[0]);
console.log('Script path:\n - ' + process.argv[1]);
console.log('Command-line arguments:');
for (let i = 2 ; i < process.argv.length ; i++) {
console.log(' - ' + process.argv[i]);
}
Which will produce this output:
$ node print_args.js --flag Hello World
Node.js path:
- /Users/razvan/.nvm/versions/node/v22.14.0/bin/node
Script path:
- /Users/razvan/Projects/test/print_args.js
Command-line arguments:
- --flag
- Hello
- World
The anatomy of shell commands
A shell command is generally composed of:
- A command name.
- A list of optional flags.
- A list of optional arguments.
The command name
When working with Node.js, the command name is usually composed of the node command followed by the script you want to execute.
For example:
$ node script.js
The command flags
The command flags, also referred to as options, are used to modify the default behavior of a command. They usually start with a hyphen - or double hyphen --, followed by a letter, a number, or a word.
For example:
$ node script.js --help
The command arguments
The command positional arguments, which typically follow the command name and any present command flags, are used to provide additional information or data required by the command to complete its task. They are usually raw text data or file paths.
For example:
$ node logs.js --json logs/output.txt
Note: While flags are most often used as standalone switches (e.g.,
--verbose), they can also take their own arguments to configure the command.For example:
$ node server.js --port 3000 --env config/.env
Define and parse command-line arguments
In Node.js, the commands-line flags and arguments of a script can be parsed using the parseArgs() method of the util core module.
const { parseArgs } = require('node:util');
const { values, positionals } = parseArgs({
options,
allowPositionals?
});
Where:
valuesis an object mapping the parsed flags and their values.positionalsis an array containing positional arguments.optionsis an object used to describe flags.allowPositionalsis an optional boolean used to enable positional arguments. Defaults tofalse.
To define command flags, you can use the following syntax:
{
options: {
flag: {
type,
multiple?,
short?,
default?
},
...
}
}
Where:
flagis a string describing the name of the flag in the long format (e.g.,'long'->'--long').typeis a string describing the type of the argument's value. Must be either'string'or'boolean'.multipleis a boolean indicating whether this option can be provided multiple times. Iftrue, all values are collected in an array, otherwise, values for the option are last-wins. Defaults tofalse.shortis a single character describing the name of the flag in the short format (e.g.,'l'->'-l').defaultis either a string, a boolean, or an array of either type. It must be of the same type as thetypeproperty. When multiple istrue, it must be an array.
Note: It is usually recommended to implement a
--helpor-hflag to display a concise guide on how to use the CLI, including common examples and usage patterns.
Example
Let's consider this script that generate a random password.
const { parseArgs } = require('node:util');
const { randomInt } = require('node:crypto');
let values;
let positionals;
let length = 10;
let charset;
try {
// Define CLI flags
({ values, positionals } = parseArgs({
options: {
help: {
type: 'boolean',
short: 'h',
default: false
},
length: {
type: 'string',
short: 'l'
},
charset: {
type: 'string',
short: 'c'
},
},
allowPositionals: true
}));
// Parse the --length flag
if (values.length) {
if (isNaN(values.length)) {
throw new Error('--length must be an integer');
}
length = Number(values.length);
if (!Number.isInteger(length)) {
throw new Error('--length must be an integer');
}
}
// Parse the --charset flag
if (values.charset) {
if (values.charset !== 'alpha' && values.charset !== 'alnum') {
throw new Error('--charset must be "alpha" or "alnum"');
}
charset = values.charset;
}
} catch(error) {
// Output the error
console.error(error.message);
// Exit with failure
process.exit(1);
}
// Handle the --help flag
if (values.help) {
console.log(`USAGE
$ node ./pwdgen.js [--help] [--charset] --length
DESCRIPTION
This script outputs a random password of a specified length.
--length, -l An integer used to set the password length.
--charset, -c An optional string used to limit the character set.
"alpha" will generate [a-zA-Z]
"alnum" will generate [a-zA-Z0-9]
undefined will generate [a-zA-Z0-9!@#$%^&*()_-+=<>?]`);
process.exit(0);
}
// Define the list of accepted characters
let characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-+=<>?'
// Define an empty password string
let password = '';
// Add random characters to the password string
while (password.length < length) {
const randchar = characters[randomInt(0, characters.length)];
if (
!charset ||
charset === 'alpha' && /^[a-zA-Z]$/.test(randchar) ||
charset === 'alnum' && /^[a-zA-Z0-9]$/.test(randchar)
) {
password += randchar;
}
}
// Output the password string
console.log(password);
// Exit with success
process.exitCode = 0;
return;
Which when executed will produce this output:
$ node ./pwdgen.js --help
USAGE
$ node ./pwdgen.js [--help] [--charset] --length
DESCRIPTION
This script outputs a random password of a specified length.
--length, -l An integer used to set the password length.
--charset, -c An optional string used to limit the character set.
"alpha" will generate [a-zA-Z]
"alnum" will generate [a-zA-Z0-9]
undefined will generate [a-zA-Z0-9!@#$%^&*()_-+=<>?]
$ node ./pwdgen.js
OlJXc*nu6Y
$ node ./pwdgen.js --length 15
A083Fz7o%xegyfV
$ node ./pwdgen.js --charset alpha
uzSHDlPeol
$ node ./pwdgen.js --length 8 --charset alnum
CGzif6Lc