Skip to content

Instantly share code, notes, and snippets.

@SantoshCode
Last active November 5, 2021 15:08
Show Gist options
  • Save SantoshCode/acbfd6fa1e645e715a4090e0d6fd3b67 to your computer and use it in GitHub Desktop.
Save SantoshCode/acbfd6fa1e645e715a4090e0d6fd3b67 to your computer and use it in GitHub Desktop.
Instructions to create a simple cli tool using nodejs & npm

Creating Nodejs cli

$ mkdir sample
$ cd sample
$ npm init
$ touch index.js

index.js

#!/usr/bin/env node
console.log(`Hi there`)

package.json

{
  "name": "santosh",
  "version": "1.0.0",
  "bin": {
      "santosh": "index.js"
  },
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Santosh Subedi",
  "license": "ISC"
}

Note: santosh will be our command to execute our index.js file

"bin": {
    "santosh": "index.js"
},

Now Link our project to our executable folder.

$ cd sample
$ npm link

Note: This command will link our project as global executable. It is like installing a npm package globally npm i -g santosh

Testing

$ santosh

Hi there

Note: Your sample folder will be sync with the command. So any changes inside that project folder will reflect on that command execution.

Publish to npm

$ npm adduser

or,

$ npm login
$ npm publish

Note: If you are publishing next feature (major/minor/patch). You have to change version value inside package.json file. But npm provides us a simple way

$ cd sample
$ npm version major/minor/patch
$ npm publish

Also remember

Always clear git logs (meaning make your local changes to remote git repo updated before publishing to npm).

e.g.

$ git add .
$ git commit -m "IMPROVE: Clear console added"
$ git push origin master
$ npm version minor
$ npm publish
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment