Feeling inspired to create a NodeJS command-line script to solve a specific issue? Do you want to ship your command-line as an installable package?

You already wrote a nodeJS command-line scripts, and you want to make it a npm package ? Here is how to do it. You can also read a more complete explanation here

Create a package

Create an empty directory first, then the package

mkdir directoryName
npm init

A few questions will be prompted, for the package.json creation (like name, version …).
Please choose index.js for the entry point so that the rest of this tutorial works fine.

package.json

NodeJS command-line script

Create a NodeJS script called index.js that does what you want, and add this at the top: #!/usr/bin/env node

For instance, a script that echoes the first argument passed to you command line:
package.json

Give a CLI name

At the end of your package.json, add the “bin” after the "license": "ISC" (don’t forget to add a , after "ISC"):
package.json

Test it locally

chmod +x index.js           # Make the file executable
npm link

Then type

myCommand hello

And it should return hello

What now ?

  1. Remove the global link using npm unlink: this will keep your environment clean

  2. Publish your package on https://www.npmjs.com if your script may be useful for others! Note that once published, you don’t have to do

    chmod +x index.js
    npm link
    

    anylonger since it is part of the npm install !

Reference: