Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 39 ยท Projects and Practice

Project: A Command-Line Tool

Build a todo-scanner CLI with Bun: parse arguments with util.parseArgs, scan files with Bun.Glob, format output, set exit codes, read stdin, add a shebang and compile to a single executable.

Bun is a very good fit for command-line tools: it starts in milliseconds, runs TypeScript without a build step, has a built-in glob, file API and shell, and can compile your script into one executable. In this project you build todofind, a tool that scans a folder for TODO and FIXME comments and prints a report, with options, proper exit codes and JSON output for other programs to consume.

Bun is not available on this site, so the Bun script is read-only. The runnable blocks run the pure logic (argument parsing and comment extraction) on Node 24. util.parseArgs behaves the same on both runtimes.

What the tool does

TEXT
todofind [options] [folder]

  -t, --tag <name>     tag to look for (repeatable, default TODO and FIXME)
  -g, --glob <pattern> files to scan (default "**/*.{ts,js,py,md}")
      --json           print JSON instead of text
      --max <n>        exit with code 1 if more than n items are found
  -h, --help           show help

Exit codes matter for CLIs. 0 means success, 1 means the check failed (too many items, so CI can fail the build), and 2 means usage errors such as an unknown option. Text output goes to stdout, errors and warnings to stderr, so users can pipe the report without noise.

Parsing arguments

You do not need a library. parseArgs from node:util (supported by Bun) parses flags, values and positionals, and with strict: true rejects unknown options:

TypeScript
import { parseArgs } from "node:util";

const { values, positionals } = parseArgs({
  args: Bun.argv.slice(2),      // [bun, script, ...userArgs]
  options: {
    tag:  { type: "string", short: "t", multiple: true },
    glob: { type: "string", short: "g", default: "**/*.{ts,js,py,md}" },
    json: { type: "boolean", default: false },
    max:  { type: "string" },
    help: { type: "boolean", short: "h", default: false },
  },
  allowPositionals: true,
  strict: true,
});

Bun.argv holds the full argument list (process.argv works too). Options defined as multiple: true collect into arrays. Numbers arrive as strings, so convert and validate them yourself.

Node.js parseArgs: flags, values, positionals, errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Scanning files

Bun.Glob matches file patterns, and Bun.file(...).text() reads each file. Collect matches as plain objects so they are easy to print or serialize:

TypeScript
type Item = { file: string; line: number; tag: string; text: string };

async function scan(folder: string, pattern: string, tags: string[]): Promise<Item[]> {
  const glob = new Bun.Glob(pattern);
  const items: Item[] = [];
  for await (const rel of glob.scan({ cwd: folder, onlyFiles: true })) {
    if (rel.includes("node_modules/") || rel.startsWith(".git/")) continue;
    const text = await Bun.file(`${folder}/${rel}`).text();
    items.push(...extract(text, rel, tags));
  }
  return items.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
}

The extraction itself is pure string work, so we can run it here and unit-test it in the real project:

Node.js extract(): find TODO and FIXME comments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The regular expression is deliberately simple: it looks for a comment marker first, then the tag. Real tools use a parser per language; mention that limit in your help text.

Formatting and exit codes

TypeScript
const items = await scan(folder, values.glob!, tags);

if (values.json) {
  console.log(JSON.stringify(items, null, 2));
} else if (items.length === 0) {
  console.log("Nothing to do.");
} else {
  for (const it of items) console.log(`${it.file}:${it.line}  [${it.tag}] ${it.text}`);
  console.log(`\n${items.length} item(s)`);
}

const max = values.max === undefined ? Infinity : Number(values.max);
if (items.length > max) {
  console.error(`Found ${items.length} items, more than the allowed ${max}.`);
  process.exit(1);
}

Use console.error for diagnostics so redirected stdout stays clean: todofind --json > report.json writes only JSON.

The complete script

TypeScript
#!/usr/bin/env bun
// todofind.ts
import { parseArgs } from "node:util";

const HELP = `Usage: todofind [options] [folder]
  -t, --tag <name>      tag to find (repeatable, default TODO, FIXME)
  -g, --glob <pattern>  files to scan
      --json            JSON output
      --max <n>         exit 1 when more than n items exist
  -h, --help            show this help`;

function fatal(message: string): never {
  console.error(`todofind: ${message}\n\n${HELP}`);
  process.exit(2);
}

let parsed;
try {
  parsed = parseArgs({
    args: Bun.argv.slice(2),
    options: {
      tag: { type: "string", short: "t", multiple: true },
      glob: { type: "string", short: "g", default: "**/*.{ts,js,py,md}" },
      json: { type: "boolean", default: false },
      max: { type: "string" },
      help: { type: "boolean", short: "h", default: false },
    },
    allowPositionals: true,
    strict: true,
  });
} catch (err) {
  fatal((err as Error).message);
}

const { values, positionals } = parsed;
if (values.help) {
  console.log(HELP);
  process.exit(0);
}

if (values.max !== undefined && !/^\d+$/.test(values.max)) fatal("--max must be a whole number");
const folder = positionals[0] ?? ".";
const tags = values.tag?.length ? values.tag : ["TODO", "FIXME"];

// ... scan(), extract() and the output code from above go here ...

Make it executable (chmod +x todofind.ts) and run ./todofind.ts src. The first line #!/usr/bin/env bun tells the operating system which interpreter to use. To distribute it as an npm CLI, add "bin": { "todofind": "./todofind.ts" } to package.json; users who install it need Bun. For people without Bun, compile it:

TEXT
bun build --compile --minify ./todofind.ts --outfile todofind
bun build --compile --target=bun-windows-x64 ./todofind.ts --outfile todofind.exe

See Docker and single-file executables for the options.

Reading from standard input

A good CLI also works in pipelines. If no folder is given and stdin is not a terminal, read the text from stdin:

TypeScript
if (!process.stdin.isTTY && positionals.length === 0) {
  const text = await Bun.stdin.text();
  const items = extract(text, "<stdin>", tags);
  // print as above
}

Now git diff | todofind reports the markers in a diff. Interactive prompts (prompt("Continue? ")) must only be used when process.stdin.isTTY is true, or the tool will hang in CI.

Testing a CLI

Put the logic (extract, scan, option handling) in functions that return data, and keep only the thin main in the script. Then bun test checks the functions directly, and one end-to-end test launches the script with Bun.spawn(["bun", "todofind.ts", "--json", "fixtures"]), reading stdout and proc.exited for the exit code (shell and spawn).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which exit code convention is common for command-line tools?

    Shells and CI treat 0 as success, so failures must exit non-zero.
  2. 2. Why print errors with console.error?

    Separate streams let users capture results without mixing in diagnostics.
  3. 3. What does the first line #!/usr/bin/env bun do?

    It is a shebang; with the executable bit set, ./script.ts runs through Bun.
  4. 4. How do you make a CLI usable by people without Bun installed?

    --compile bundles the runtime and your code into one binary, with cross-platform targets.

Summary

  • util.parseArgs handles flags, values, repeatable options and positionals; strict mode rejects unknown options.
  • Bun.Glob + Bun.file().text() scan trees quickly; keep extraction logic pure and testable.
  • Exit 0 on success, 1 on a failed check, 2 on usage errors; results to stdout, diagnostics to stderr.
  • Support pipes via Bun.stdin; guard prompts with process.stdin.isTTY.
  • Ship with a shebang, an npm bin entry or bun build --compile.

Next: Practice Exercises and Challenges