# 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](https://www.geeksforgeeks.org/nodejs-path-module/))

  * Only `path.join()` is enough for this project.

* **File System Module (`fs`)** ([Read article](https://www.geeksforgeeks.org/node-js-file-system/))

  * 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](https://www.geeksforgeeks.org/javascript-basics/)
2. [Higher-order functions](https://www.geeksforgeeks.org/javascript-higher-order-functions/)
3. [Callback functions](https://www.geeksforgeeks.org/javascript-callbacks/)

---

## 🛠️ 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:

```js
// 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`](https://www.npmjs.com/package/commander), a popular package to build real CLIs in Node.js.

---

## 🧑‍💻 Final CLI Tool (with Commander)

```js
// 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:

```bash
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

```bash
There are 8 words in the file.
```

---

### 📸 Screenshots

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1746904387043/f4c0d2e7-4a25-4335-9da8-fb7dc0df1c58.png)

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1746903860216/abe24811-f17e-4407-8eb4-9cd117900dbd.png)

