Making Node cli

πŸš€ Making a CLI with Node.js

I recently started learning Node.js and JavaScript basics. To strengthen my understanding of backend and JavaScript fundamentals, we're going to build a simple CLI tool from scratch.


πŸ“˜ Theory

1. What is CLI?

A CLI (Command-Line Interface) is a text-based interface that allows users to interact with a computer's operating system or software by typing commands. (Think of cmd in Windows)

Source: Google


2. Required Node.js Knowledge

  • Path Module (Read article)

    • Only path.join() is enough for this project.
  • File System Module (fs) (Read article)

    • Only fs.readFile and fs.writeFile are needed.
    • Use asynchronous methods for both.

3. Required JavaScript Knowledge

  • Basic Syntax

    • Writing console.log("Hello, World!")
  • Control Flow

    • if, else
    • switch
  • Loops

    • for, while
  • Functions

    • Function declarations & calls
    • Arrow functions (=>)
    • Callback functions
    • Higher-order functions
  • Async JS and DOM (Optional)

    • Promises
    • Async/Await
    • Basic DOM manipulation (optional)

πŸ“š Resources

  1. JavaScript Basics
  2. Higher-order functions
  3. Callback functions

πŸ› οΈ Let's Start Coding

βœ… Step 1: Read a File Using Pure Node.js

Create two files:

  • a.txt β†’ Add some sample text.
  • index.js β†’ Paste the following code:
// CLI to count words using plain Node.js
const fs = require('fs');

function ReadFile(filename) {
  fs.readFile(filename, 'utf-8', (err, data) => {
    if (err) {
      console.log("Error reading file:", err);
      return;
    }

    let total = 0;
    for (let i = 0; i < data.length; i++) {
      if (data[i] === " ") total++;
    }
    console.log("Total words (approx.):", total + 1); // +1 to include the last word
  });
}

// Static call
ReadFile('a.txt');

// Dynamic usage
ReadFile(process.argv[2]);  // e.g., `node index.js a.txt`

❌ Problem

This approach gives you the basic logic but it isn't a real CLI tool β€” there’s:

  • No help or description.
  • No argument validation.
  • No commands like count_word, etc.

βœ… Solution: Use the commander Library

We’ll now use commander, a popular package to build real CLIs in Node.js.


πŸ§‘β€πŸ’» Final CLI Tool (with Commander)

// CLI with commander to count words
const { Command } = require('commander');
const fs = require('fs');

const program = new Command();

program
  .name('Count')
  .description("CLI to count how many words are there in a file")
  .version('0.0.1');

// Define the CLI command
program
  .command('count_word')
  .description('Count how many words are in the given file')
  .argument('<file>', 'File to count words from')
  .action((file) => {
    fs.readFile(file, 'utf-8', (err, data) => {
      if (err) {
        console.log("Error:", err.message);
        return;
      }

      // Use regex to split and count actual words
      const words = data.trim().split(/\s+/);
      console.log(`There are ${words.length} words in the file.`);
    });
  });

program.parse();

πŸ§ͺ How to Use

Run this in the terminal:

node server.js count_word "C:\\Users\\HP\\Desktop\\my-corhot\\node-js\\b.txt"

βœ… Output

πŸ‘‡ Input File (b.txt)

Hey there!
This is a test file.

πŸ–₯ Terminal Output

There are 8 words in the file.

πŸ“Έ Screenshots

0
Subscribe to my newsletter

Read articles from the_OldSchool_coder directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

the_OldSchool_coder
the_OldSchool_coder

I am a passionate full-stack web developer with expertise in designing, developing, and maintaining scalable web applications. With a strong foundation in both front-end and back-end technologies, I specialize in creating dynamic user experiences and robust server-side solutions. Proficient in modern frameworks like React, Angular, Node.js, and Django, I thrive on crafting efficient, clean code and optimizing performance. Whether building RESTful APIs, designing responsive interfaces, or deploying applications to the cloud, I bring a results-driven approach to every project.Let me know if you'd like to customize it further, perhaps including your specialties or experience level!