Today I want to show you how to make a command-line tool using an npm package I created called Divine Star Commander or just dscom.
It is meant to be an all-in one package for creating a command-line application. It handles program input, user input, displaying colored text, boxes, progress bars, and more. It is well documented and all the code is commented. So, if you are building the tool with TypeScript you will get information on what exactly each function and directive does.
So, let’s begin. The first thing you will need to do is start a new node project and install a few dev dependencies:
>npm init >npm i --save-dev typescript @types/node >npm i --save dscom
Next, we need to update the package.json file and create a few folders. The first is the bin folder which will be the place where the compiled typescript will be exported and the entry point for the application. The second folder we will need is a folder for the code we will be writing. For this example, I will be calling it “ts”.
So now in the ts folder run this command:
Now we need to make a few changes to the tsconfig file:
So, from here we can create an index.ts file in the ts directory and then run this command:
Okay from here I am going to make a very basic example I will read in the user’s input to add two numbers together. It should give you a basic idea of what the package can do.
This will prompt you to enter two numbers and re-ask you if you fail to enter the correct number. It will then show the two numbers in a bright cyan color and sleep for a little bit. Then show the sum of the two numbers in a bright green text. Note about this example: You still have to process the input yourself as all input actually received by the console is in a string format. I may make it so it can automatically return a number but that would require me to separate the number input type into int and float types.
Next, I will show you how to add program params to our app. Let’s say we want to add a flag to either add or subtract the numbers. We can do that easily like so:
As you can see the package makes it very easy to create a command-line application. It handles a lot of the heavy lifting for you. If you want to learn about all of its features please check out the wiki on GitHub.