Making a Node.js Command-Line Utility

Today, we’re going to cover how to turn your Node.js script into a native command-line utility, and then how to share it with the world using NPM (Node Package Manager). In the video, I’m using the trial-and-error approach to show you everything that is required and show the errors you might encounter along the way if you forget a step. It’s actually quite simple.

Cheat Sheet

Turn your Node script into a native command-line utility

  1. Wrap your Node script in a package by putting it in its own directory and creating the package.json file (name and version are the only required properties)
  2. Expose your script as a command-line utility by adding the bin property to the package.json file, mapping the command-line utility’s name to your script
  3. In your script, add the shebang: #!/usr/bin/env node
  4. npm link to install the package globally

Share it with the world

  1. In the package.json file, add the preferGlobal property set to true.
  2. npm adduser
  3. npm publish

Unshare it with the world

  1. npm unpublish mypackage --force

Example package.json file (minimal)

"name": "mypackage",
"version": "0.0.1",
"preferGlobal": "true",
"bin": {
"mycommand": "./relative/path/to/script.js"

Author: Guest

Author: Guest Sometimes someone asks if they can write for the blog. They may want to just work on their own writing chops, get their foot in the blogging door, or maybe they want to show off something they've done. In any case, they are a guest author and this post happens to be written by one; please enjoy the hard work they've done to put this article together.