Create CLI in Nodejs
I wanted to create a command line tool for sharing files for some time now, but given all the things we have to go through to do that same was a hassle. But after getting to know Node.js more, I have never thought it would be done with so much ease. NPM helps us to make it an easy and time saving process.
After creating and publishing my first CLI module , I want to share these simple steps to create your own CLI module. In this blog, we will see how to make a node script do things on the command line.
We will also see an example of a file-share module.
Step 1 : Node and NPM installation
Here We assume that you have NodeJs and NPM (Node package manager) installed on your computer. If not, please install both before we proceed further.
Installing NodeJs and NPM is a simple process, to do so follow this link.
Step 2 : Creating project and package.json configuration
Now, create a project and run npm init .
NPM will ask you to enter some configuration values for your project. You can provide input or can choose to skip it by pressing enter key. You can edit these entries anytime in future. It will create a template package.json file.
NPM uses package.json file to know about your project and to install its dependencies.
Now make following changes in package.json file :
- remove main key.
- add preferGlobal key and set it to true. Now this module will always be installed globally.
- add bin object which maps commands to files. After installation, npm will map my-command to index.js file.
Example package.json :
[js]
{
"name": "test-cli",
"version": "1.0.0",
"description": "",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"preferGlobal" : true,
"bin" : {
"my-command" : "index.js"
}
}
[/js]
Step 3 : Creating index.js
Now create index.js file and add the following code in it.
[js]
#! /usr/bin/env node
console.log("my-command-cli running …");
[/js]
(#!) at the start of first line also known as the shebang, makes the script executable with what follows it.
/bin/env looks at the current environment. We have added a “bin” key in package.json file to tell Node where it can find the file to execute as a command (my-command).
Step 4 : Installation and testing
To install this module on your computer, run npm link .
Run my-command in terminal/command window to test your command and you will see the following output :
[js]
my-command-cli running …
[/js]
Now you can implement index.js as per your requirements.
Use case : file-share module
Following the above described approach, I have created and published a npm module named file-share .
You can use it for sharing files and directories over LAN.
Github link of file-share module.