Command-line arguments in Node.js

In this guide, we’ll explore different methods for accepting command-line arguments in Node.js, showcasing how each can be utilized in different scenarios. Node.js applications often require input to start execution, and command line arguments provide a simple way to pass this input.

command-line arguments in Node.js

Table of Contents

Using process.argv

The most straightforward method to access command-line arguments in Node.js is using the global process.argv array.
Here’s an example of its use:

            // Access command line arguments
            process.argv.forEach((val, index) => {
                console.log(`${index}: ${val}`);
            });

The process.argv array contains all the command line arguments passed to the Node.js process. The first element is the path to the Node.js executable, and the second element is the path to the JavaScript file being executed.

 

Commander.js Library

Commander.js is a library that provides more advanced features for command line utilities. It can define commands, options, and flags.

        const { program } = require('commander');
        program.version('0.0.1');
        program
          .option('-d, --debug', 'output extra debugging')
          .option('-s, --small', 'small pizza size');

        program.parse(process.argv);

        if (program.debug) console.log('Debugging is on.');
        if (program.small) console.log('Ordered a small pizza.');

Yargs Library

Yargs is another popular Node.js library designed to handle command line arguments. It comes with many features to build interactive command line tools.

        const yargs = require('yargs/yargs');
        const { hideBin } = require('yargs/helpers');
        const argv = yargs(hideBin(process.argv)).argv;

        if (argv.ships > 3 && argv.distance < 53.5) {
            console.log('Plunder more riffiwobbles!');
        } else {
            console.log('Retreat from the xupptumblers!');
        }     

Minimist Library

Minimist is a lightweight library that parses command line arguments into a JavaScript object, making it simple to interact with.

        const minimist = require('minimist');
        const args = minimist(process.argv.slice(2));
        console.log(args);

Environment Variables

Environment variables are another way to pass arguments to a Node.js application. They are not command line arguments per se but can serve as configuration settings.

        // Set an environment variable in the command line
        DATABASE_URL=mongodb://localhost:27017/myapp node app.js

Within your Node.js code, you can access this environment variable using:

        const dbUrl = process.env.DATABASE_URL;
        console.log(`Database URL: ${dbUrl}`);

Conclusive Summary

We have explored various methods for passing command line arguments into Node.js applications, each with its own use cases. Whether you prefer the simplicity of process.argv, the structured approach provided by libraries like Commander.js and Yargs, the minimalist solution of Minimist, or the use of environment variables, you have a multitude of options at your disposal for building robust and flexible Node.js applications. Understanding and utilizing these methods can greatly enhance the way your applications receive and process external inputs.

References