Setting Up the Basics
So, you're ready to build your own command-line tool with Node.js? Awesome! We're about to unlock the magic of automation right from your terminal. Whether you're new to CLI (Command-Line Interface) tools or just need a refresher, this section will walk you through the basics, step by step. Grab your keyboard and let’s get started!
1.1 Your First Node.js CLI Tool
Let’s kick things off with the most basic project you can imagine—a simple "Hello World" CLI tool. Why? Because even though it’s basic, it’ll show you the entire flow of building a Node.js-based CLI tool from scratch.
Why Node.js?
Great question! Node.js is perfect for CLI tools because:
- JavaScript everywhere – You’re probably already familiar with JS, so why not use it here?
- Easy to set up – No need for fancy configurations or massive frameworks.
- Cross-platform – It works on Windows, macOS, and Linux. Everyone’s happy.
Let’s get started!
Step 1: Setting Up Node.js
Before diving into coding, make sure Node.js is installed on your machine. If it’s not, head over to Node.js and download the latest stable version. Once that’s done, let’s check if it’s installed properly. Open your terminal and type:
node -v
You should see something like v14.x.x
(depending on the version). If that’s all good, we’re ready to roll.
Step 2: Create Your First CLI Tool
Now, let’s jump into writing the actual code. Open your terminal, navigate to a folder where you want to create your project, and run:
mkdir my-first-cli
cd my-first-cli
npm init -y
This will create a new folder called my-first-cli
, and the npm init -y
will quickly generate a basic package.json
file for you.
Now, let’s create our script. Inside your project folder, create a file called index.js
:
touch index.js
Open that file and type in the following code:
#!/usr/bin/env node
console.log("Hello World from your first CLI tool!");
That #!/usr/bin/env node
bit at the top tells your terminal that this is a Node.js script. Now, let’s make this file executable. Run this command:
chmod +x index.js
Then, to test it, you can run:
./index.js
Boom! You should see "Hello World from your first CLI tool!" pop up in your terminal. Congratulations, you’ve just made your first CLI tool!
1.2 How to Run Your Script via the Terminal
Running your script by typing ./index.js
every time is cool and all, but wouldn’t it be nicer if you could just type a simple command like greet
and get the same result? Let’s make that happen.
Step 1: Update package.json
In your package.json
file, add this line under the bin
field:
"bin": {
"greet": "./index.js"
}
This tells npm that when we install this package globally, we want to create a greet
command that will run our script.
Step 2: Install Globally
Now, we’re going to install your CLI tool globally on your system, so it’s available anywhere. Run this:
npm link
Now, from any directory, type:
greet
And just like magic, your terminal will display "Hello World from your first CLI tool!"
1.3 Exploring process.argv
: Getting Inputs from Users
Now that we’ve got a basic CLI tool, let’s make it interactive. We can get inputs from the user directly from the command line using process.argv
. Let’s modify our script to accept a name and greet the user personally.
In your index.js
file, update the code to:
#!/usr/bin/env node
const args = process.argv.slice(2);
const name = args[0] || 'World';
console.log(`Hello, ${name}!`);
Now, if you run:
greet John
It will print:
Hello, John!
If you don’t pass a name, it’ll default to "World." Pretty neat, right?
1.4 Fun Tip: Add a Joke with an External API
Let’s take things a step further and add some fun to our tool. How about making your CLI tool tell a random joke? We’ll use an external API to fetch a joke and display it in the terminal.
First, install the axios
package to make HTTP requests:
npm install axios
Now, modify your index.js
to fetch a joke from an API:
#!/usr/bin/env node
const axios = require('axios');
const args = process.argv.slice(2);
const name = args[0] || 'World';
console.log(`Hello, ${name}!`);
axios.get('https://official-joke-api.appspot.com/random_joke')
.then(response => {
const joke = response.data;
console.log(`${joke.setup} - ${joke.punchline}`);
})
.catch(error => {
console.log("Oops, couldn't fetch a joke at this time.");
});
Now, every time you run:
greet
You’ll get a greeting and a joke! The terminal might show something like:
Hello, World!
Why don't skeletons fight each other? - They don't have the guts.
And that’s it! You’ve now built an interactive CLI tool that fetches real-time data from the web.
1.5 Making It Interactive: Mini Quiz Game
For our final trick in this section, let’s make a mini quiz game where the user answers questions through the terminal.
Step 1: Install Inquirer.js
We’ll use inquirer.js
to handle interactive prompts. Install it with:
npm install inquirer
Step 2: Build the Quiz Game
Update your index.js
file to create a quiz game:
#!/usr/bin/env node
const inquirer = require('inquirer');
inquirer.prompt([
{
type: 'list',
name: 'planet',
message: 'Which planet is closest to the Sun?',
choices: ['Earth', 'Mars', 'Mercury', 'Venus'],
}
])
.then(answers => {
if (answers.planet === 'Mercury') {
console.log('Correct! Mercury is the closest planet to the Sun.');
} else {
console.log('Oops! The correct answer is Mercury.');
}
})
.catch(error => {
console.log('Something went wrong!', error);
});
Now, if you run:
greet
Your CLI tool will ask the user a question and give them feedback based on their answer!
Wrapping Up Tutorial 1
In this section, you’ve built a basic CLI tool that:
- Prints a custom greeting,
- Takes inputs from users,
- Fetches data from an API (a joke, no less!), and
- Even runs an interactive quiz.
These are the building blocks you’ll use to create more advanced tools. Up next, we’ll dive into automating real-life tasks—turning your CLI tool into something truly useful for your day-to-day workflow. Stay tuned!