Read command-line arguments in Node.js

Read positional arguments with process.argv, parse named options with util.parseArgs, and pass arguments through npm scripts correctly.

Best practices
Illustration of an event loop and asynchronous tasks

For a Node program launched from a script file, process.argv starts with the Node executable and script path. Application arguments follow at index 2.

node task.cjs foo "hello world"
// task.cjs
process.argv.forEach((value, index) => {
  console.log(`${index}: ${value}`);
});
const args = process.argv.slice(2);
console.log(args[0]); // foo
console.log(args[1]); // hello world

This layout describes a script-file invocation. Special modes such as node -e do not supply the same script-path slot, so do not blindly apply the slice to every Node invocation.

Parse named options

util.parseArgs() was added in Node 18.3 and 16.17, and became stable in Node 20. Use a supported Node release and declare the options your program accepts:

// options.cjs
const { parseArgs } = require('node:util');
const { values, positionals } = parseArgs({
  options: {
    name: { type: 'string' },
    force: { type: 'boolean', short: 'f' }
  },
  allowPositionals: true
});
console.log({ name: values.name, force: values.force, positionals });
node options.cjs --name=Tom -f input.txt

The parser validates declared option types and, by default, rejects unknown options. For a larger CLI, libraries such as Commander provide subcommands, help output, and version handling; a smaller parser such as minimist may suit a simpler interface. Check the selected library's behavior rather than treating their APIs as interchangeable.

Validate values and preserve argument boundaries

Raw process.argv entries are strings. Convert numeric values explicitly and check their range; Number() alone will also accept values such as an empty string. A parsed boolean flag, by contrast, is a boolean produced by the parser.

Quote arguments containing spaces according to your shell. When passing options through an npm script, separate npm's options from the script's options:

npm run build -- --mode=production

Do not put credentials in command-line arguments: process listings and shell history may expose them. Environment variables are another delivery mechanism, but can also appear in diagnostics or be inherited by child processes. Use your deployment's secret-handling facilities where appropriate.

If non-ASCII text is corrupted, inspect the terminal encoding, shell, font, and receiving program. Changing a Windows code page may address one part of the path, but is not a universal fix. Avoid mutating process.argv for parsing; keep your own argument array instead.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting