/nodejs, shell, JavaScript, script

Create NodeJS command line script or app

I wanted to write a simple script that would convert multiple files from one encoding to another. I didn't want anything big or running in the browser. Command line script seemed like the right approach. Coming from a web developer background my first thought was a script written in PHP and converted to a command line app. Just saying that sounds awful. After a bit of googling, it turned out NodeJS is surprisingly easy and straightforward to write command line apps.

Initiate the app

Running npm init will ask you a few basic questions about your app and result in creating package.json file.

$ npm init

name: cldemo
version: 0.0.1
description: Simple command line script
entry point: index.js
test command:
git repository:
keywords:
author: SixBytesUnder
license: (ISC)

Edit the newly created package.json and add "bin" section. The property key will be the command you'll type in to run your app. In our case cldemo. The value is a relative path to the entry point file. That's the file our code will reside in.

...
"author": "SixBytesUnder",
"license": "ISC",
"bin": {
  "cldemo": "./index.js"
}

Next, create index.js file or any other file you have provided as an "entry point" above. Paste example code show below.

#!/usr/bin/env node
'use strict';

// your whole code goes here
console.log('Hello World!')

The most basic command line script is done.

Register your script

Next command will register your app as a shell command. Note, on Windows you need to open command prompt as an admin, navigate to the home directory of your app and run below.

$ npm install -g

That's it, it's a simple as that. Now you should be able to run your script from command line globally.

$ cldemo
Hello World!

If you make any changes to your source files, remember to register your app again, so that latest version is copied to the global path.

To uninstall your script just type:

$ npm uninstall -g cldemo