ProductPromotion
Logo

0x3d.Site

is designed for aggregating information.

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!

Creating CLI Tools with Node.js

Learn how to create powerful, professional-grade command-line tools with Node.js in this comprehensive course. From setting up your environment and automating real-life tasks to distributing your tool and adding advanced features like async tasks, multiple commands, configuration files, and API integrations, this guide covers it all. Perfect for developers looking to simplify workflows and build scalable tools, this course offers clear, practical steps with a focus on usability and real-world applications.
  1. Collections 😎
  2. Frequently Asked Question's 🤯
  3. Shortcuts 🥱
  4. Error Solutions 🤬

Tools

available to use.

Providers

to have an visit.

Made with ❤️

to provide resources in various ares.
  1. Home
  2. About us
  3. Contact us
  4. Privacy Policy
  5. Terms and Conditions

Resouces

to browse on more.
0x3d
https://www.0x3d.site/
0x3d is designed for aggregating information.
NodeJS
https://nodejs.0x3d.site/
NodeJS Online Directory
Cross Platform
https://cross-platform.0x3d.site/
Cross Platform Online Directory
Open Source
https://open-source.0x3d.site/
Open Source Online Directory
Analytics
https://analytics.0x3d.site/
Analytics Online Directory
JavaScript
https://javascript.0x3d.site/
JavaScript Online Directory
GoLang
https://golang.0x3d.site/
GoLang Online Directory
Python
https://python.0x3d.site/
Python Online Directory
Swift
https://swift.0x3d.site/
Swift Online Directory
Rust
https://rust.0x3d.site/
Rust Online Directory
Scala
https://scala.0x3d.site/
Scala Online Directory
Ruby
https://ruby.0x3d.site/
Ruby Online Directory
Clojure
https://clojure.0x3d.site/
Clojure Online Directory
Elixir
https://elixir.0x3d.site/
Elixir Online Directory
Elm
https://elm.0x3d.site/
Elm Online Directory
Lua
https://lua.0x3d.site/
Lua Online Directory
C Programming
https://c-programming.0x3d.site/
C Programming Online Directory
C++ Programming
https://cpp-programming.0x3d.site/
C++ Programming Online Directory
R Programming
https://r-programming.0x3d.site/
R Programming Online Directory
Perl
https://perl.0x3d.site/
Perl Online Directory
Java
https://java.0x3d.site/
Java Online Directory
Kotlin
https://kotlin.0x3d.site/
Kotlin Online Directory
PHP
https://php.0x3d.site/
PHP Online Directory
React JS
https://react.0x3d.site/
React JS Online Directory
Angular
https://angular.0x3d.site/
Angular JS Online Directory