Mittwoch, 14. Dezember 2011

NPM Modules Step by Step (Part II) - Command Line Tools

Having created our first module and having published as described in this blog post (Introduction into Node Modules Part I) wouldn't it be cool if we could use this extremely sophisticated capitalize and decapitalize functions as a command line tool as well?

Lets say we want to be able to do this on the command line:

Hector:~ $ cap -c foo (yields => FOO)
Hector:~ $ cap -d FOO (yields => foo)

Where cap -c capitalizes the given argument and -d decapitalizes it.

Actually that is very easy.
First we have to change our package.json file

Please take care of the 2 changes that we made against the previous version of that file.
  1. we changed the version from "0.1.0" to "0.2.0" (line 5)
    If we don't change that version to a higher version than the one that has been published previously npm will complain about that fact.
  2. We need to add the key "bin" and the name of the command line tool and the associated script that shall be executed on calling that command (line 18-21)
Lets start hacking on our command line tool. First of all we will create a subdirectory for our command line tool. The standard name for the command line directory is "bin". This is no hard requirement however most npm packages seem to adhere to it. So will we.

Hector:~/capitalize $ mkdir bin
Hector:~/capitalize j$ cd bin
Hector:~/capitalize/bin $ touch cap.js

now add the following code to ~/capitalize/bin/cap.js

Please take care of to a hash-bang in line 1. This is needed (at least under *nix systems).
Lines 4 and 5 are the ones that return the command line arguments.
Argument 0 is the node itself and argument 1 is the script being executed (in this case cap.js).

We are almost done. Actually our script wont be executed (on *nix systems) we have forgotten to change the execution rights. Please do

Hector:~/capitalize/bin $ chmod +x cap.js
Hector:~/capitalize/bin $ ls -ls
total 0
0 -rwxr-xr-x  1 robertj  staff  0 14 Dez 14:20 cap.js

Now we move back to our directory containing our package.json and publish it.

Hector:~/capitalize/bin $ cd ..
Hector:~/capitalize $ npm publish

Finally install the package globally

Hector:~ $ sudo npm install capitalize -g
/opt/local/bin/cap -> /opt/local/lib/node_modules/capitalize/bin/cap.js
capitalize@0.2.0 /opt/local/lib/node_modules/capitalize 

this will install the the command cap as a global link into your global node_modules directory.

I hope you enjoyed the show. Next time: "installation/deinstallation scripts"


  1. I think theres' an error here:
    var capitalize = require("../index.js");
    Did you mean "main.js"?