Table Of Contents
npx
npx is a tool shipped with npm@5.2.0 and newer that allows you to execute any command from the npm registry (ex: npx create-react-app) without need to install it locally.
Setup
An npx executable library is similar to a normal npm library. Create a new project with npm:
npm init
Now, let's create our executable file under bin folder and call it cliTest.js. All executable files must have a shebang (#! /usr/bin/env node) header:
#! /usr/bin/env node
console.log("unicorns♥")
The next step is to expose our cliTest.js as a command. Open package.json and add a bin property. It's a key-value object where the key is the command and value is the path to the executable .js file. At this point the package.json should look like this:
{
"name": "cli-npm",
"version": "1.0.0",
"bin": {
"test-cli-tool": "bin/cliTest.js"
}
}
That's all for a basic setup. Run: npm i -g to install this package locally. Open terminal and run:
npx test-cli-tool
It will output: unicorns♥
This package can also be published to npm, but this is a story for another time.
Reading arguments
All command-line arguments are accessible via argv (argument values) property of the process. To print the input add:
console.log(process.argv);
The first argument is the path to the executor, the second is the path to our executable .js file. So when parsing input you should start from the third argument (the first passed after the command). Here is a simple example:
#! /usr/bin/env node
console.log("unicorns♥");
// slice argv as we don't need the forst two elements (in this case)
const args = process.argv.slice(2, process.argv.length);
console.log(args);
const action = args[0];// first argument
const a = args[1]; // second argument
const b = args[2]; // third argument
if(action === "sum"){
// ex: npx test-cli-tool sum 5 2
// output: "Sum is: 7"
console.log("Sum is: " + (Number(a) + Number(b)));
} else if(action === "dif") {
// ex: npx test-cli-tool dif 5 2
// output: "Difference is: 3"
console.log("Difference is: " + (Number(a) - Number(b)));
} else {
console.error("Unexpected input");
}
process.exit(0);// 0 means there were no errors
This is a very primitive way of managing input. For something more sophisticated please check yargs library.
Colors
If you want to add some swag to your cli tool you should definitely make it colorful. Check here different escape codes to change colors. Ex:
const RESET = "\x1b[0m";
const GREEN = "\x1b[32m";
const YELLOW = "\x1b[33m";
const WHITE = "\x1b[37m";
const getColoredText = (text, color) => {
if(color == null){
color = WHITE;
}
// remember to add reset at the end.
return color + text + RESET;
}
console.log(getColoredText("Hello!", GREEN));
console.log(getColoredText("Hi!", YELLOW));
For some advanced colouring you can use chalk library.
To be continued...
In the next post, we will see how to execute other commands and add some spinners.
Top comments (6)
For some reason, at the first stage, it displays this:
npm ERR! code E404
npm ERR! 404 Not Found - GET registry.npmjs.org/test-cli-tool - Not found
npm ERR! 404
npm ERR! 404 'test-cli-tool@latest' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.
Hi Alexander,
Sorry for the late response, you have to install this repository in order to execute it. Try to run
npm i -g
from the root folder of your project. It will install your tool locally, and then you will be able to execute it from CLI usingnpx <your-tool-name>
.Let me know if it helped you 😀
You should update it
will work
For a project I wanted to make a cli tool like create-react-app, how can I make it, can you guide me ?
Hi Kumar. I've done a similar thing a while ago for Svelte: link. It works the same way as create-react-app: you run
npx svelte3-app
(+ some params) and it will prepare the project for you.It is very simple under the hood. It uses degit to clone svelte starter project from github to your local machine, installs the dependencies and you are ready to work with Svelte. Obviously, it is far from create-react-app, but it is a good starting point. For some more advanced things, you will have to write custom scripts.
So in general I think you need to prepare your template project (one or more based on different variants), download it (from github or whatever), and eventually manage some post download tasks (like updating package.json, rewriting some configs based on user input etc).
Hope this will serve you as a starting point.