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
- Create a script
cli.jswithconsole.log(process.argv);. - Run it with
node cli.js hello world. - The output will be
['node path', 'cli.js path', 'hello', 'world']. - Extract arguments starting from index 2:
const args = process.argv.slice(2);. - For advanced parsing, install a library like
minimistoryargs.
Tips
- Use destructuring to assign named arguments quickly when using simple parsing.
minimistconverts flags like--port=3000into an object automatically.
Common issues
- Arguments are always strings, so convert numbers with
parseInt()orNumber(). - Unescaped special characters in shell arguments may be interpreted by the shell before reaching Node.js.