node.jsnpmcommand-line

Expose a global command to run a script from node package


I am building an npm package and I want it to run with its own command.

Let's say my package's name is hello-world and it has a script named start in the package.json that runs:

node index.js

What I would like is from the command line to be able to write some custom command that will run this script.

For instance, writing hello-world in the cmd will do npm run start.

A good example is the nodemon package.


Solution


You will have to add bin field into your package.json to expose a global command which can be linked to any executable file(like js file).

Sample package.json

{
  "name": "hello-world",
  "version": "1.0.0",
  "description": "hello-world cli client",
  "bin": "index.js"
}

then your npm module should globally installed in your system as follows

npm pack (Optional.required only for local development)


npm install -g hello-world-1.0.0.tgz

Now you should able to run your script by just running the command as hello-world

Note: The executable script i.e index.js should starts with a line #!/usr/bin/env node