How to handle command line arguments in Node.js

· Category: Node.js

Short answer

Access command line arguments through process.argv, an array where the first two elements are the node executable and script path, and subsequent elements are user arguments.

Steps

  1. Create a script cli.js with console.log(process.argv);.
  2. Run it with node cli.js hello world.
  3. The output will be ['node path', 'cli.js path', 'hello', 'world'].
  4. Extract arguments starting from index 2: const args = process.argv.slice(2);.
  5. For advanced parsing, install a library like minimist or yargs.

Tips

  • Use destructuring to assign named arguments quickly when using simple parsing.
  • minimist converts flags like --port=3000 into an object automatically.

Common issues

  • Arguments are always strings, so convert numbers with parseInt() or Number().
  • Unescaped special characters in shell arguments may be interpreted by the shell before reaching Node.js.