Creating nodejs programs that run from the command line is trivial. The simplest approach is to use an executable bash shell script with a hashbang/shebang for the node interpreter. We can achieve this in three simple steps:

Step 1: Create program file

vim simple.sh

Step 2: Add hashbang to the first line of your program

#!/usr/bin/env node
console.log('hello world');

Step 3: Ensure file is executable

chmod +x simple.sh

Run your program!

./simple.sh

If you would like to write more involved command line programs with sub commands like I recommend the excellent [Commander.js](https://github.com/tj/commander.js) module.

command line programs and npm

To enable npm support for the command line program, only three extra steps are required.

Step 1: Create package.json file run npm init and follow the prompts to populate the file with project specific data

npm init

Step 2: Rename simple.sh to simple.js

mv simple.sh simple.js

Step 3: Edit package.json
Add bin & preferGlobal properties to the package.json file and remove the main property.

{
  "preferGlobal": true,
  "bin": { "simple": "simple.js" }
}

Step 4 (optional): link to the executable
Note this step is only required if the program hasn’t been installed through npm install.

npm link

Run your program!

simple

Photo credit: Zenith Z-19 Terminal