DEV Community

Avinash Tare
Avinash Tare

Posted on

How to create a global package using Node.js

Creating a global package with Node.js allows you to use your custom scripts and tools from any directory on your system. This can be extremely useful for developing command-line tools or other utilities that you want to be easily accessible. I'll walk you through creating a global Node.js package in this guide.
For this project, we make a random number generator package.

Step 1: Set Up Your Project

First, create a new directory for your project and navigate into it:

mkdir random-number-package
cd random-number-package
Enter fullscreen mode Exit fullscreen mode

Next, initialize a new Node.js project:

npm init -y
Enter fullscreen mode Exit fullscreen mode

This command will generate a package.json file with the default configuration.

Step 2: Create Your Script

  • Create a new JavaScript file that will serve as the entry point for your package. For this example, let's create a file called index.js.
  • This file will first execute when you call your package & name of the file anything.
#!/usr/bin/env node

let defualtValue = 100;
console.log(Math.floor(Math.random() * defualtValue) + 1);
Enter fullscreen mode Exit fullscreen mode
  • The #!/usr/bin/env node line add at the top of the code, which tells the system to use Node.js to run this script.It's required.
  • This js code will generate a number between 1 to 100.

Step 3: Update package.json

{
  "name": "random-number-package",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "bin": {
    "random": "index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}
Enter fullscreen mode Exit fullscreen mode
  • The bin field maps the command name (random) to the script file (index.js).

Step 4: Install your the Package Globally

npm install -g ./
Enter fullscreen mode Exit fullscreen mode

it will install your current package globally

Step 5: Run Globally

random
Enter fullscreen mode Exit fullscreen mode

output:
34

Top comments (0)