Developing NodeJS CLI tools

Lucas Katayama
Lucas Katayama
Published in
2 min readDec 5, 2016

--

This was a post from my old blog and reposting it to Medium.

I used to develop scripts using ShellScript. Today, I have a more powerfull tool: NodeJS.

In this post I’ll explain how to write Command Line Interface (CLI) tools using NodeJS.

Creating the Project

Fisrt, we are going to create the basic structure for a NodeJS project:

$ mkdir my-project && cd my-project
$ npm init
$ touch index.js

And we get an output like this:

name: (my-project)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
license: (MIT)

Creating the script

We are going to edit the index.js and make it to do something, like print an output:

#!/usr/bin/env node
console.log('Hello World!!!');

Then we edit the package.json to indicate which file is the executable (ie index.js).

Here we also define the name of the command. In this case it is going to be hello:

{
"name": "my-project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"bin" : {
"hello" : "./index.js"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Lucas Katayama <email> (http://www.lucaskatayama.com)",
"license": "MIT"
}

Installing on the system

Now we can install in 2 different ways:

  1. Linking the script to test (development environment)
  2. Doing an actual install

1. Symbolic Install

Let’s do the first one, to test the script. In this way we can link the command while we develop and the execute it. So it is possible to change and execute without running the install process all over again.

In the project directory, we run:

$ sudo npm link

And then run the command (remember the name we give in the earlier steps):

$ hello

The output should be:

Hello World!!!

If we change the index.js to something like:

#!/usr/bin/env node
console.log("Good Bye World!!!");

And then execute the command again, we should get:

~/my-project $ hello
Good Bye World!!!

So, we don’t need to re-execute npm link.
Just be careful, because the executable will be pointing to the folder my-project

System Installation

To do the actual install, we do:

$ sudo npm install -g

Which will do the isntall in the lib folder from your system.

If you publish you module to the NPM registry, with the name my-project then you can install using:

$ sudo npm install -g my-project

Which will search for the module in the NPM registry, download it and then install in your system.

References

So this is it. Thanks.. See ya.

--

--