2

I am using commander@2.9.0. Attached the code below

package.json

{
  "name": "commandtools",
  "version": "1.0.0",
  "description": "A command line example",
  "main": "index.js",
  "scripts": {
         "test": "node index.js hello"
  },
  "author": "aaa <aaa@xxx.com>",
  "license": "MIT",
  "bin": {
    "cmdtools":"./index.js"
  },
  "dependencies": {
    "commander": "^2.9.0"
  }
}

index.js

var program = require('commander');

program
    .version('0.0.1')
        .usage('<input>')
            .parse(process.argv);

            if(!program.args.length) {
                        program.help();
            } else {
                        console.log('Input: ' + program.args);
            }

On executing in command-line,

cmdtools Hello

index.js file opens without any output in the command-line

On executing,

npm test

The output is

Input: hello

What am I missing ?

Muthu
  • 337
  • 6
  • 19

2 Answers2

0

Your code outputs the arguments passed in the command line.

npm test outputs Input: hello, because npm test actually runs node index.js hello. If you change node index.js hello to node index.js banana the output will be Input: banana.

More about CLI arguments and how to access them here: https://nodejs.org/api/process.html#process_process_argv

cmdtools command does not output anything, because there are no arguments passed to the index.js file.

When running cmdtools command you passed an argument to the cmdtools command and not to index.js. Nothing is outputted, because program.help() does not output anything to the console. You can test this by running console.log('test') instead of program.help().

Deividas
  • 6,437
  • 2
  • 26
  • 27
  • Understood about the scripts part. I am wondering why the `cmdtools Hello` doesn't output neither `Input: Hello` nor `help content`, instead opens the index.js file? I hope there must be an output. Correct me if am wrong. – Muthu Feb 21 '17 at 12:46
  • I passed an argument `Hello`. Also in case if It don't pass any arguments it must output the help content right? Why does index.js file opens?Also what should be done to pass argument `Hello` with `cmdtools` – Muthu Feb 21 '17 at 12:51
  • Updated my answer. – Deividas Feb 21 '17 at 13:07
0

The error in the npm module is

  • Installed the package globally, but didn't execute npm link
  • So, executed npm link and tried cmdtools Hello and got the expected output
Muthu
  • 337
  • 6
  • 19