I'm using commander.js command like this ./index.js --project mono --type item --title newInvoice --comments 'Creates an invoice' --write, Now I'm using the command through npm run item newInvoice by setting some options in package.json file like this
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "snapshot": "node --max-old-space-size=10240 ./scripts/snapshot.js",
    "item": "./index.js --project mono --type item --title",
    "config": "./index.js --project mono --type config --title"
}
But whenever I'm trying to get the --write option with npm using npm run item newInvoice --write it's showing undefined for --write
Source Code:
#!/usr/bin/env node
const fs = require('fs');
const program = require('commander');
require('colors');
program
  .version('0.1.0')
  .option('--project [project]', 'Specifies the project name', 'mono')
  .option('--type [type]', 'Type of code to generate, either "item" or "config"', /^(config|item)$/, 'config')
  .option('--title [title]', 'Title of the item or config', 'untitled')
  .option('--comments [comments]', 'Configs: describe the config', '@todo description/comments')
  .option('--write', 'Write the source code to a new file in the expected path')
  .option('--read', 'To see what would be written the source code to a new file in the expected path')
  .parse(process.argv);
console.log(program.write, program.read); //=> undefined undefined
Can anyone help me how to use commander js command with npm?
When you run your npm run command you need to utilize the special -- option to demarcate the end of any option(s) that may belong to the npm run command itself (e.g. --silent), and the beginning of the argument(s) that are to be passed to the end of the npm script.
Run the following command instead:
npm run item -- newInvoice --write
Given the aforementioned command and the command currently defined your npm script named item they essentially form the following compound command prior to execution:
./index.js --project mono --type item --title newInvoice --write
                                              ^          ^
The npm run documentation states the following:
As of [email protected], you can use custom arguments when executing scripts. The special option
--is used by getopt to delimit the end of the options. npm will pass all the arguments after the--directly to your script.
and it's usage syntax is defined in the Synopsis section as:
npm run-script <command> [--silent] [-- <args>...] ^^
Note: It's not possible to add the -- option to the npm script itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With