Programming guides, explanations and reader checklists on whilenetworking.com

Building a CLI Todo App: Parsing Arguments, File Storage, and Command Execution in Node.js

In the world of software development, command-line interfaces (CLIs) remain a powerful tool for automation, scripting, and rapid prototyping. For IT students…

In the world of software development, command-line interfaces (CLIs) remain a powerful tool for automation, scripting, and rapid prototyping. For IT students and junior engineers, mastering the art of building a CLI application is a crucial step toward understanding how programs interact with the operating system. This guide walks you through constructing a robust CLI Todo application in Node.js. We will cover parsing user arguments to handle different commands, implementing file storage for data persistence, and safely executing shell commands when necessary. By the end of this tutorial, you will have a functional script that can add tasks, list them, mark them as complete, and save progress to a local file.

Setting Up Your Environment and Project Structure

Before writing any logic, it is essential to establish a clean development environment. This ensures your project is reproducible and follows industry best practices from day one.

  1. Initialize the Project: Open your terminal and navigate to your desired directory. Run npm init -y to generate a default package.json. This file tracks dependencies and scripts.
  2. Install Dependencies: We will use commander for argument parsing, as it is lightweight and widely adopted. Run npm install commander.
  3. Create the Entry Point: Create a file named index.js. This will be your application’s entry point when run via node index.js.
mkdir todo-cli
cd todo-cli
npm init -y
npm install commander

This structure separates concerns: the package manager handles dependencies, while index.js contains your business logic. Keeping code in a dedicated directory also makes version control with Git significantly easier.

Parsing Arguments with Commander

A CLI application must understand user intent before taking action. The commander library simplifies this by allowing us to define specific flags and sub-commands. We will implement three primary actions: add, list, and complete.

Define your commands in the main file. When a user runs node index.js add "Buy groceries", the parser captures the command (add) and the argument (Buy groceries).

const { Command } = require('commander');
const program = new Command();

program
  .name('todo')
  .description('A simple CLI todo application')
  .version('0.0.1');

// Define the 'add' command
program
  .command('add <task>')
  .description('Add a new task to the list')
  .action((task) => {
    console.log(`Task added: ${task}`);
    // Logic to save will follow
  });

// Define the 'list' command
program
  .command('list')
  .description('List all tasks')
  .action(() => {
    console.log('Current tasks:');
    // Logic to read file will follow
  });

// Define the 'complete' command
program
  .command('complete <task>')
  .description('Mark a task as complete')
  .action((task) => {
    console.log(`Task completed: ${task}`);
    // Logic to update status will follow
  });

program.parse();

Here, the .command() method registers a new route for your CLI. The <task> parameter is required; if the user forgets it, commander will throw an error and display usage instructions. This immediate feedback loop is vital for debugging during development.

Implementing File Storage for Persistence

Without file storage, a CLI app loses all data upon termination. We will use a simple JSON file named todos.json to persist the state of our application. This approach avoids the complexity of setting up a database server for small projects while demonstrating fundamental I/O operations.

We need two helper functions: one to write data and one to read it. Always ensure the file exists before reading to prevent runtime errors.

const fs = require('fs');
const path = require('path');

const DATA_FILE = path.resolve(__dirname, 'todos.json');

function saveTodo(todo) {
  let todos = [];

  // Check if file exists; if not, initialize empty array
  if (!fs.existsSync(DATA_FILE)) {
    fs.writeFileSync(DATA_FILE, JSON.stringify([], null, 2));
  }

  // Read existing data
  const fileContent = fs.readFileSync(DATA_FILE, 'utf8');
  todos = JSON.parse(fileContent);

  // Append new task
  todos.push(todo);

  // Write back to file with indentation for readability
  fs.writeFileSync(DATA_FILE, JSON.stringify(todos, null, 2));
}

function loadTodos() {
  if (!fs.existsSync(DATA_FILE)) return [];

  const fileContent = fs.readFileSync(DATA_FILE, 'utf8');
  return JSON.parse(fileContent);
}

Illustrative Output: When a task is added and the app restarts, the todos.json file will contain:

[
  { "id": 1, "text": "Buy groceries", "completed": false },
  { "id": 2, "text": "Learn Node.js", "completed": true }
]

Safely Handling Command Execution and Error Management

While our basic app uses simple logic, real-world CLIs often need to execute system commands or handle edge cases. When interacting with the file system or shell, safety is paramount. Always validate inputs before writing to disk to prevent injection attacks or corruption.

For example, if you were extending this app to execute shell commands based on user input, you would strictly sanitize that input. Never pass raw user strings directly into child_process.execSync without validation.

// Example of safe error handling during file operations
function performSafeAction(actionName, callback) {
  try {
    callback();
    console.log(`[SUCCESS] ${actionName} completed.`);
  } catch (error) {
    // Log to stderr for CLI apps
    console.error(`[ERROR] Failed to perform ${actionName}: ${error.message}`);
    process.exit(1); // Exit with error code
  }
}

// Usage within your action handlers
program.command('add <task>')
  .action((task) => {
    performSafeAction('Adding task', () => {
      saveTodo({ id: Date.now(), text: task, completed: false });
      console.log(`✓ Added: ${task}`);
    });
  });

Common Mistakes and Fixes:
* Mistake: Not checking if todos.json exists before reading. Fix: Use fs.existsSync() as shown above.
* Mistake: Writing JSON without formatting. Fix: Use JSON.stringify(data, null, 2) to make the file human-readable and easier to debug manually.
* Mistake: Forgetting to handle the case where a task already exists. Fix: Implement a check in your save function to either update the existing ID or generate a new unique ID.

Testing and Verification Steps

Before deploying any CLI tool, verification is non-negotiable. You should test the application manually first, then consider writing unit tests using Jest for complex logic.

Verification Checklist:
1. Empty State Test: Run node index.js list. Ensure it outputs “Current tasks:” with no errors, even if the file doesn’t exist yet.
2. Add Operation: Run node index.js add "Test Task". Check that todos.json is created (or updated) and contains the new entry.
3. List Operation: Run node index.js list again. Verify the output reflects the added task.
4. Error Handling: Attempt to run a command with missing arguments (e.g., node index.js add). Ensure the application displays the help message or an appropriate error rather than crashing silently.

Industry Application and Student Practice Task

For students, this project serves as a foundational exercise in modular design. For industry practitioners, similar patterns are used in DevOps tools, build scripts, and internal utility apps that automate routine tasks without requiring a GUI.

Student Practice Task:
Extend your application to accept an optional flag --priority with values “high”, “medium”, or “low”. Modify the JSON structure to store this priority level. Add a new command filter <priority> that lists only tasks matching that priority. Implement error handling for invalid priority strings.

By completing these steps, you have moved beyond theoretical knowledge into practical application. You now understand how to parse arguments, manage persistent storage, handle errors gracefully, and structure a Node.js project for real-world usage. Remember to initialize your Git repository (git init) and commit your work regularly to track your progress.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.