CPCODELAB
Node.js

Building a Simple CLI Tool

11 min read

Building a Simple CLI Tool

Node.js is excellent for command-line tools. You can read arguments, interact with the file system, and even prompt for input. A CLI tool is a great first project — you use process.argv, fs, path, and process.exit all in one place.

js
#!/usr/bin/env node
// wordcount.js — count words in a file

const fs = require("fs/promises");
const path = require("path");

async function main() {
  const args = process.argv.slice(2);

  if (args.length === 0) {
    console.error("Usage: node wordcount.js <file>");
    process.exit(1);
  }

  const filePath = path.resolve(args[0]);

  let content;
  try {
    content = await fs.readFile(filePath, "utf8");
  } catch (err) {
    console.error(`Cannot read file: ${err.message}`);
    process.exit(1);
  }

  const lines = content.split("\n").length;
  const words = content.split(/\s+/).filter(Boolean).length;
  const chars = content.length;

  console.log(`File: ${path.basename(filePath)}`);
  console.log(`Lines: ${lines}`);
  console.log(`Words: ${words}`);
  console.log(`Characters: ${chars}`);
}

main();

Making the Script Executable

bash
# Add shebang line at top of file (already done above)
# Then make it executable:
chmod +x wordcount.js

# Run it directly
./wordcount.js README.md

# Or expose it as an npm bin
# In package.json: "bin": { "wordcount": "./wordcount.js" }

For larger CLI tools, explore the commander or yargs npm packages — they handle argument parsing, help text generation, and sub-commands automatically. CPCODELAB's backend modules build several CLI utilities to cement these fundamentals.

Ready to test yourself?
Practice Node.js— quiz & coding exercises