Explain Codes LogoExplain Codes Logo

How do I pass command line arguments to a Node.js program?

javascript
command-line-arguments
argument-parsing
node-js
Nikita BarsukovbyNikita Barsukov·Aug 26, 2024
TLDR

Access command line arguments in a Node.js program using process.argv.slice(2). This overlooks the node path and script path, providing a clean array of just the arguments:

const args = process.argv.slice(2); console.log(args); // Outputs: ['arg1', 'arg2', ...] // And so on and so forth...

To execute your script along with arguments:

node script.js arg1 arg2

For better efficiency in parsing key-value pairs and flags, bring minimist into play:

const argv = require('minimist')(process.argv.slice(2)); console.log(argv); // { _: [], key: 'value', a: true, b: 5 } // Got'em all, right?

Invoke your script with the above arguments like:

node script.js --key=value -a -b 5

Walkthrough of command-line arguments

In Node.js, leveraging command line arguments yields flexible inputs and dynamic configurations. Here's a quick guide to various argument parsing techniques in different scenarios.

Fetching values in a jiffy

For bare minimal tasks, indexing directly from process.argv will do the trick:

const port = process.argv[2]; // So, this is our port number huh!

In the terminal, run:

node server.js 8080 // Boom! There's your port number!

However, it's tricky for complex scenarios.

Structure argument parsing like a boss

For a tidier way, try parsing libraries like yargs or commander.js. They facilitate more organized and maintainable syscall inputs.

const { program } = require('commander'); program .option('-d, --debug', 'output extra debugging') .option('-s, --small', 'small pizza size') // Who doesn't like pizza, right? .parse(process.argv); if (program.debug) console.log('Captain Debug reporting for duty!');

Run with debugging mode:

node pizza.js --debug // Piping hot pizza with debug topping!

Using minimist for a souped-up parsing

To make sense of multiple key-value arguments, minimist provides a clean and compact structure:

const argv = require('minimist')(process.argv.slice(2)); console.log('Running in mode:', argv.mode); // Who's the boss now? argv.mode, of course!

This flow can be used to input arguments:

node process.js --mode=production // Production it is!

CLI argument tips and tricks

The key to efficient CLI applications is mastering how to handle input arguments. Let me share some exclusive tips and tricks:

Interacting CLI using vorpal.js

For interactive CLIs, vorpal.js can make your application more interactive and user-friendly:

const vorpal = require('vorpal')(); vorpal .command('order <foodItems...>') // Variadic arguments, yum! .action(function ({ foodItems }) { this.log(`Order confirmed: ${foodItems.join(', ')}`); // Fast-food Node.js style! }); vorpal.delimiter('food-bot$').show(); // Don't be shy, order away!

Starting an interactive session:

node interactive.js food-bot$ order pizza fries coke // Who wouldn't want a pizza!

Cross-platform compatibility with environment variables

The cross-env package sets and uses environment variables across platforms, a lifesaver for configuring your application's environment:

npx cross-env NODE_ENV=production node app.js

Peer into those pesky arguments

Lastly, to inspect the parsed arguments, there's nothing better than console.dir:

console.dir(process.argv.slice(2), { 'colors': true }); // A rainbow of arguments!

Execute your script and behold a color-coded output of arguments!

Pre-processing for win

To overcome complex scenarios, try the trick of pre-processing arguments before they hit the parsers. This strategy might include splitting comma-separated values or decoding URLs:

const rawArgs = process.argv.slice(2); const processedArgs = rawArgs.map(arg => decodeURIComponent(arg)); // Goodbye, encodings! // Now you're ready to parse along!