Exploring the options variables within CLI commander Js action

As a newcomer to developing CLI apps, I've chosen to work with ts-node and commander. However, I'm currently facing a challenge in understanding how to access the options that users pass into my command action.


program
  .version(version)
  .name(name)
  .option('-sm, --something', 'does something', false)
  .description(description);

program.command('clear-environment').action(() => {
  
  /// Seeking ways to view the user-passed usage options here
  if (options.contains('-sm')) {
    // perform certain actions
  }

  (async () => {
    const userFeedback = await getPromptAnswers(CLEAR_ENV_QUESTIONS);
    if (userFeedback?.deleteAll) {
      cleanEnvironment();
    }
  })();
});

I'm uncertain if this approach is correct, so any advice or guidance on this matter would be greatly appreciated.

Answer №1

A configuration object (of type any for TypeScript) is included as the final argument of the operation. For instance, in:

program
  .command('example <arg1> <arg2>')
  .option('-c, --count', 'Return a count')
  .option('-v, --verbose', 'Be verbose')
  .action((arg1, arg2, configuration) => {
    console.log(arg1, arg2, configuration)
  })

If you run the command:

npm run cli example cool stuff -- --verbose --count

You will see this result produced:

cool stuff { verbose: true, count: true }

Answer №2

The action handler receives the command's options and arguments, along with the command itself. In this example, the action handler only deals with options and not positional arguments.

const { Command } = require('commander');
const program = new Command();

program
  .description('A program for ordering pizza')
  .option('-p, --peppers', 'Add peppers')
  .option('-c, --cheese <type>', 'Specify the type of cheese to add', 'marble')
  .option('-C, --no-cheese', 'Do not include any cheese')
  .action(options => {
    console.log(options);
  })

program.parse();
$ node index.js -p -c cheddar
{ cheese: 'cheddar', peppers: true }

(Note: I am part of the Commander maintenance team.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for TypeScript to preserve the return type while consolidating multiple classes or objects of functions in a reducer method?

Describing my issue with the title was challenging, but here it is: I have several objects that follow this structure: type TUtilityFunction = {[key: string]: <T>(a: T, b: any) => T} For example: class UtilityA{ DoSomeWork = function (arg1: So ...

define a variable within a v-for loop

Example of Code <div v-for="item in dataItems"> <div v-if="enableEdit"> <input type="text" v-model="name"> </div> <div v-else> {{name}} </div> <button @click="enableEdit = true">click</button> This ...

Hold off until the RxJS dispatch is resolved

I am working on integrating a "next step" feature into my Angular 6 webapp. When the user clicks the "next step" button, the frontend triggers an action to update the database with the data in the store, another action to retrieve processed data from a Spr ...

Join the nested Observables array

I have an array that holds objects, each containing two properties where one is an observable value. let myArray = [{def: 'name1', value: EventEmitter_}, {def: 'name2', value: EventEmitter_}] My goal is to subscribe to the observables ...

Aurelia TypeScript app experiencing compatibility issues with Safari version 7.1, runs smoothly on versions 8 onwards

Our team developed an application using the Aurelia framework that utilizes ES6 decorators. While the app works smoothly on Chrome, Firefox, and Safari versions 8 and above, it encounters difficulties on Safari 7.1. What steps should we take to resolve th ...

Retrieve the document id along with the corresponding data from a collection

Retrieving data from the collection leads and displaying all documents in an HTML table. Upon clicking, I need to extract the document ID of the clicked item as it serves as the sole primary key. P.S I am able to obtain records of all documents in an arra ...

How can a property be made mandatory in Typescript when another property is set as optional?

Currently, I am unsure about what to search for in order to fulfill the following requirement. Specifically, I am utilizing the given type for react props: interface ComponentProps { message : string, minValue? : number, minValueValidationMessage? ...

Separate an array in TypeScript based on the sign of each number, and then replace the empty spaces with null objects

Hey, I'm facing a little issue, I have an Array of objects and my goal is to split them based on the sign of numbers. The objects should then be dynamically stored in different Arrays while retaining their index and getting padded with zeros at the b ...

Creating a digital collection using Vue, Typescript, and Webpack

A short while back, I made the decision to transform my Vue project into a library in order to make it easier to reuse the components across different projects. Following some guidelines, I successfully converted the project into a library. However, when ...

The utilization of the Angular date pipe significantly impacts the way dates are

When I use the pipe date:'MM/dd/YYYY' to display the date 2022-01-01T00:00:00, it shows as 1/01/2021 instead of 1/01/2022. This issue only occurs with this specific date. Why does this happen? The value of pharmacyRestrictionDate is 2022-01-01T0 ...

Using redux action in the onPaginationChange function instead of setPaginationState in the given example for the TanStack table - is there a way to

Provided this sample Is there a way to utilize by dispatching a redux action rather than using useState - setPaginationState? onPaginationChange: state => dispatch(browseItemModalActions.setPagination(state)) An error is appearing in the console: ...

What is the best way to incorporate vertical scrolling into a React material table?

I'm having trouble getting vertical scroll to work with my material table in React Typescript. Horizontal scroll is functioning properly for large data, but I'm stuck on implementing the vertical scroll. Here's my code: {isLoading ? ...

Tips for effectively using ngOnChanges in Angular 2 to validate inputs without causing the 'Expression has changed after it was checked' error

I attempted to create my own custom component with basic validation using regex that can be passed as input to the component. There are two scenarios to consider: one where the form is initially empty (new item form) and another where data is already prese ...

Holding off on completing a task until the outcomes of two parallel API requests are received

Upon page load, I have two asynchronous API calls that need to be completed before I can calculate the percentage change of their returned values. To ensure both APIs have been called successfully and the total variables are populated, I am currently using ...

What is the best approach to handling an undefined quantity of input FormControls within Angular?

I have a unique task in my Angular application where I need to collect an unspecified number of entries, such as names, into a list. My goal is to convert this list of names into an array. To facilitate this process, I would like to offer users the abilit ...

Creating a custom definition file for TypeScript

Currently, I am facing an issue with a third-party library that provides global functions similar to jQuery ($ .functionName()), but unfortunately there is no definition file available. Due to this, my attempt to write my own file has been unsuccessful as ...

Tips for managing numerous nested subscriptions

Looking to extract the id parameter from the route, fetch the corresponding task, and then its parent if applicable. Angular CLI: 7.1.4 Node: 11.6.0 OS: linux x64 Angular: 7.1.4 @angular-devkit/architect 0.11.4 @angula ...

Error: Unexpected token < occurs when using SVG require in Jest

I'm struggling to locate the source of this error. Currently, I am working with Typescript in React and using Jest and Enzyme for unit testing. Below is a snippet from my Package.json file: "scripts": { "start": "node server.js", "bundle": ...

React Hook Form: Reset function triggers changes across all controllers on the page

I encountered an issue with using the reset function to clear my form. When I invoke the reset function, both of my form selects, which are wrapped by a Controller, get cleared even though I only defined default value for one of them. Is there a way to pr ...

Exploring Angular 8: Connecting elements to an array filled with objects

My goal is to achieve the following: https://i.sstatic.net/TQeKN.png In my form, I have 2 fields: description and price. When the plus button is clicked, additional input fields (Input 2 and Price 2) are generated dynamically. I want to bind these field ...