Create Node JS Command-Line from Scratch.

The goal of this tutorial to create a command-line application with node js that works globally on cross-operating systems. Just for fun, we will create a simple bitcoin command line that returns the price of the current bitcoin.

Implementing the script logic:

First of all, let’s implement the logic of our application before we convert the script into a global command line. In this example, we want to get the price of bitcoin. I will use https://blockchain.info/ticker API to fetch the realtime price.


const https = require("https");

function fetchBTCData() {
  return new Promise((resolve, reject) => {
    let body = "";
    https.get(
      {
        hostname: "blockchain.info",
        path: "/de/ticker",
        agent: false
      },
      res => {
        res.setEncoding("utf8");
        res.on("data", function(chunk) {
          body += chunk;
        });
        res.on("end", function() {
          resolve(body);
        });
      }
    );
  });
}

(async () => {
  const data = JSON.parse(await fetchBTCData());
  console.log(data.USD.last);
})();

I am using https node module to connect to the API, then parse the JSON response and simply console.log the bitcoin price in USD.

Now we can run the script via node command:

node index.js

Create the command line

There are four steps that I use to create a global command line:

  • Create a package.json file with the “bin” section.
  • Add comment to the JS file to allow it to be treated like executable
  • Change the JS file permission ( Linux + Mac ).
  • Node link our file

1. Add the bin section.

In this step, we need to have the package.json if it does not exist, we can create it by npm

npm init -y

Now open your package.json and add "bin": "index.js" where index.js is your main js script. My file looks like:

{
  "name": "bitcoin",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bin": "index.js"
}

2. Add Comment to the JS File:

Now we create an empty Javascript file index.js then we simply add the following comment:

#!/usr/bin/env node

This comment essentially tells our machine that this file needs to be executed by nods js.

3. The File Permission.

This step is only required for Linux and Mac. We need to add execute permission to our index.js Simply run:

chmod +x index.js

4. Node Link the Script

npm link

This will take the current project and make it available everywhere and on every directory on our machine.

Now if we run bitcoin anywhere in the terminal, we should get the current price of bitcoin without the need to run by node command and the need to specify the script name

Note that the command name bitcoin it’s the same what of what you have in your package.json under name

You can check the full code on Github.

You may also like

Leave a comment