Lesson 27 / 28

Building a Tiny CLI Tool

Combine argv, fs, and a shebang into a runnable command-line tool.

A word-count CLI

Read a file named on the command line and report its word count.

#!/usr/bin/env node
import { readFile } from "node:fs/promises";

const filePath = process.argv[2];
if (!filePath) {
  console.error("Usage: wordcount <file>");
  process.exit(1);
}

const text = await readFile(filePath, "utf8");
const words = text.trim().split(/\s+/).length;
console.log(`${filePath}: ${words} words`);

Output:

notes.txt: 42 words

Making it executable

The #!/usr/bin/env node shebang lets the OS run the file directly, without typing node first.

chmod +x wordcount.js
./wordcount.js notes.txt