More Node.js answers

by Danny
Published 2 min read

Node.js puts command-line arguments in process.argv. Learn how to read them, and how to parse flags and options properly with the built-in util.parseArgs.

The short answer

#

Arguments are in process.argv, an array of strings. The first two entries are the path to the Node.js binary and the path to your script, so the arguments you typed start at index 2. For anything beyond one or two positional values, use the built-in parseArgs from node:util instead of parsing by hand.


_10
// node greet.js Ada --shout
_10
const args = process.argv.slice(2);
_10
console.log(args); // [ 'Ada', '--shout' ]

Why it happens

#

The operating system passes a program its command line as a list of strings. Node.js exposes that list unchanged as process.argv, including the executable and script path, which is why the slice is needed. Everything is a string: --port 3000 gives you '3000', not a number, and Node.js does not know which values are flags and which are positional.

That is fine for a quick script, but hand-written parsing tends to break on --port=3000, short flags like -p, or a flag that appears twice. util.parseArgs handles those cases and is stable in every supported Node.js release, so you no longer need a package for simple tools.

How to fix it

#

Use util.parseArgs for flags and options

Describe the options you accept, and parseArgs returns values for options and positionals for everything else.


_13
import { parseArgs } from 'node:util';
_13
_13
const { values, positionals } = parseArgs({
_13
options: {
_13
port: { type: 'string', short: 'p', default: '3000' },
_13
verbose: { type: 'boolean', short: 'v', default: false },
_13
tag: { type: 'string', multiple: true },
_13
},
_13
allowPositionals: true,
_13
});
_13
_13
const port = Number(values.port);
_13
console.log({ port, verbose: values.verbose, tags: values.tag, files: positionals });


_10
node server.js -p 8080 --verbose --tag a --tag b input.txt

By default parseArgs runs in strict mode, so an unknown option or a missing value throws an error. Catch it and print a usage message rather than a stack trace.


_10
try {
_10
const { values } = parseArgs({ options: { port: { type: 'string' } } });
_10
} catch (error) {
_10
console.error(error.message);
_10
console.error('Usage: node server.js --port <number>');
_10
process.exit(1);
_10
}

Read process.argv directly for one or two values

For a script that takes a single file name, destructuring is clear enough.


_10
const [inputPath] = process.argv.slice(2);
_10
_10
if (!inputPath) {
_10
console.error('Usage: node count-lines.js <file>');
_10
process.exit(1);
_10
}

Pass arguments through npm scripts

When you run a script with npm run, put -- before your arguments. Without it, npm treats flags such as --port as options for npm itself.


_10
npm run start -- --port 8080

Reach for a library for large CLIs

If you need subcommands, generated help text or shell completion, a library such as Commander or yargs is still worth it. For a handful of flags, parseArgs keeps your tool dependency-free.

Common pitfalls

#
  • Forgetting the slice(2) and treating the script path as the first argument.
  • Comparing a value to a number. Arguments are always strings, so convert with Number() and check the result with Number.isNaN().
  • Expecting parseArgs to convert types. type is only 'string' or 'boolean'; anything else is up to you.
  • Missing the -- in npm run, so your flags silently vanish.
  • Putting Node.js options after the script name. node app.js --inspect passes --inspect to your script; use node --inspect app.js instead.
#

Was this resource helpful?