Node.js: create a command line application

Node.js: create a command line application

In this article we will see how to create a simple command line application in Node.js.

In this article we will see how to create a simple command line application in Node.js.

We need the yargs module for the parsing and handling of command line arguments.

npm install yargs --save

Our application will generate a random password of length length specified by the user via the create command.

node app.js create --length=12

To achieve this, we first create a utility function which, given a length defined by an integer, generates the corresponding random password.

'use strict';

const generate = passwordLength => {
    const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@#!$%&?*%()[]{}<>|'.split('');
    let output = '';
    
    for(let i = 0; i < passwordLength; i++) {
        let char = chars[Math.floor(Math.random() * (chars.length - 1))];
        output += char;
    }

    return output;
};

module.exports = generate;

At this point we need to define the create command with the mandatory option length which must be an integer.

'use strict';

const yargs = require('yargs');
const createPassword = require('./lib/generate');

yargs.command({
    command: 'create',
    describe: 'Generate a password',
    builder: {
        length: {
            describe: 'Password length',
            demandOption: true,
            type: 'number'
        }
    },
    handler(argv) {
        console.log(createPassword(argv.length));
    }
});

yargs.parse();

The command() method defines a command. Inside, the builder object defines the command options. In our case the length option is mandatory (demandOption) and must be a number (type).

The handler() method defines a callback to handle the command. Its only argument, argv, is an object literal having as its property all the options defined above whose values will be those entered by the user.