How to Create an NPX Tool
Tags: javascript, node, programming, tutorial
Published: 2022-03-09 20:02:21

---
title: How to Create an NPX Tool
published: true
date: 2022-03-08 07:58:36 UTC
tags: Javascript,node,programming,tutorial
canonical_url: https://blog.shahednasser.com/how-to-create-a-npx-tool/
cover_image: https://blog.shahednasser.com/static/73becc36a58a429e67df83eb34b64ef9/How-to-Create-an-NPX-Tool.jpg
---

_This was originally published on [my personal blog](https://blog.shahednasser.com/how-to-create-a-npx-tool/)._

[NPM](https://www.npmjs.com) (stands for Node Package Manager) is widely used by web developers to install and manage a variety of JavaScript libraries. It's a necessity for more websites nowadays. It comes installed with Node.js by default.

However, you've probably seen a lot of libraries or frameworks instructing you to use NPX when installing their packages. [React](https://reactjs.org/docs/create-a-new-react-app.html) even has a warning that clarifies for developers that using NPX is not a typo.

NPX is a package runner that allows you to run CLI tools or executables hosted on NPM without the need to install them with NPM first.

For example, previously you'd need to install `create-react-app` globally on your system, then run `create-react-app my-website`.

Ever since NPM v5.2, there's no need to install `create-react-app` globally (and it's recommended that you don't). You can simply run `npx create-react-app my-website` and the same script will run to create your React app.

In this tutorial, you'll learn how you can create your own NPX tool. The tool you'll create through this tutorial is pretty simple – it'll only multiply 2 or more numbers. You'll also learn how you can use your tool locally and how you can publish it on the NPM registry for others to use.

## Prerequisites 

This is pretty obvious, but you need [Node.js](https://nodejs.dev) installed to go through this tutorial. Installing Node.js will install in turn NPM and NPX.

## Project Setup

Create a new directory that will hold your tool:

```
mkdir multiply-tool
```

Next, initialize your project with NPM:

```
npm init
```

You'll be asked a few questions about the package such as package name and author name. After you fill them out, a `package.json` file will be created in the current directory.

## Create the Bin File

When you create a CLI tool or an executable file, you need to create a file and include it in your package.json under the `bin` field.

Create the directory `bin` and inside that directory create the file `index.js` with the following content:

```
#! /usr/bin/env node
console.log("Hello, World!");
```

All this file will do (for now) is print "Hello, World!" to your command line or terminal. However, the important thing to note here is the following line:

```
#! /usr/bin/env node
```

This line should be added to all files that will be executed through the command line. It's called a [Shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)), and basically, it specifies what interpreter the file should be passed to for execution in Unix-like systems.

Next, in `package.json` add the new field `bin`:

```
"bin": {
	"multiply": "bin/index.js"
},
```

This means that when the user runs `npx <package_name>` the script `bin/index.js` will run.

## Test it Locally

To test it locally, first, install the package globally in your system:

```
npm i -g
```

You should run this command inside the directory that holds your package.

Then, in your terminal, run the following command to run your NPX tool:

```
npx multiply
```

Here, `multiply` is the name of the package. If you named your package something else be sure to put the name of the package.

When you run the command, you'll see "Hello, World!" printed in your terminal.

![How to Create an NPX Tool](https://backend.shahednasser.com/content/images/2022/03/Screen-Shot-2022-03-03-at-12.16.27-PM.png)

## Using Arguments

In this section, you'll implement the functionality of the `multiply` package. This package should accept at least two arguments (if the arguments are less than 2, the user will get an error). Then, it will multiply all the arguments. If the result is `NaN` it means that at least one argument is not a number and the user will see an error in that case as well.

Replace the content of `bin/index.js` with the following:

```
#! /usr/bin/env node
const args = process.argv.slice(2);
if (args.length < 2) {
  console.error('Please enter at least 2 numbers');
  process.exit(1); //an error occurred
}

const total = args.reduce((previous, current) => parseFloat(current) * parseFloat(previous));

if (isNaN(total)) {
  console.error('One or more arguments are not numbers');
  process.exit(1); //an error occurred
}

console.log(total);
process.exit(0); //no errors occurred
```

A few things to note:

1. `process.argv` is used to retrieve the command line arguments. The first 2 arguments will be the interpreter running this script (which is Node in this case), and the second argument is the name of the package (which is `multiply` in this case). Any other arguments passed will be available starting from index `2`. So, to get the arguments passed by the user you need to slice the array `process.argv` and get the elements starting from the index `2`.
2. When an error occurs, you can use `process.exit(1)` to indicate that. If `process.exit` receives a value other than 0 it means that an error occurred in the CLI tool.
3. The [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) array function is used to multiply all items in the array one by one.
4. If the final result of `total` is `NaN`, the user will get an error.
5. If everything is successful, the result will be printed out and the process will exit with `0` indicating that the process ended successfully.

Let's test it out. Run the command again in your terminal passing it 2 numbers:

```
npx multiply 3 15
```

You will see the result of the multiplication in your terminal.

You can also try adding more than 2 numbers and you'll see the result. To see how the error messages work, try entering less than 2 numbers or entering strings instead of numbers.

## Publishing the Package

Now that your tool is ready, you can publish it on NPM. This step requires an NPM account, so if you don't have one make sure to [create one](https://www.npmjs.com/signup).

Then, in your terminal, run the following command to log in using your NPM account:

```
npm login
```

You'll be prompted to enter your username and password. If all is correct, you'll be logged in and you can then publish your tool.

To publish your tool, simply run:

```
npm publish
```

> Note: If you're using a GitHub repository for your project make sure to commit everything before running this command.

This will publish your tool into the NPM registry. Please note that if another package is created with the same name you'll need to change the name of your package in `package.json` then try publishing again.

## Use Your Published Package

To use your published package, you can run the same command you used earlier when running your local command:

```
npx <package_name>
```

Notice how you don't need to install your package globally in this case. You can just run it through NPX.

In my case, I had to rename my package to `multiply-tool` since `multiply` already existed in the NPM registry. Then, I ran the following command:

```
npx multiply-tool 3 15
```

And received the result of the multiplication:

![How to Create an NPX Tool](https://backend.shahednasser.com/content/images/2022/03/Screen-Shot-2022-03-03-at-12.25.53-PM-1.png)

## Update Your Package

To update your package, you can use the following command:

```
npm version <type>
```

Where `<type>` determines how to increment the version. It can be one of the following values:

1. `patch`: This will increment the last number in your version and it usually means a small change. For example, it would change the version from `1.0.0` to `1.0.1`.
2. `minor`: This will increment the second number in your version and it usually means a minor change that doesn't necessarily affect how the user uses this tool. For example, it would change the version from `1.0.0` to `1.1.0`.
3. `major`: This will increment the first number in your version it usually means that a big change happened that can affect how this tool is used. For example, it would change the version from `1.0.0` to `2.0.0`.

After running the above command run the publish command again:

```
npm publish
```

And your tool will be updated.

## Conclusion

In this tutorial, you learned how to create a tool that can be run with NPX directly without the need to install it globally. You also learned how to publish the tool and update it.

This tool is a simple tool, however, for more complex tools you can use helper libraries like [commander](https://www.npmjs.com/package/commander) and [chalk](https://www.npmjs.com/package/chalk).