Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 36 ยท Projects and Practice

Project: Publish a Small CLI

Build a small command-line tool, wire it up with the bin field and a shebang, test it, check the tarball contents and walk through a safe first publish.

In this project you will build linecount, a small command-line tool that counts lines, words and bytes in text, and take it all the way to a publish-ready package that people could run with npx linecount file.txt. Along the way you use almost everything from this chapter: exports, files, bin, scripts, a dry run and a release checklist.

The real npm publish cannot run on this site, so the project is split: the code is written and executed with Node.js here, and the packaging steps are shown as commands you run on your own machine. Every file listing below is something you can copy into a folder.

The finished layout

TEXT
linecount/
โ”œโ”€โ”€ package.json
โ”œโ”€โ”€ README.md
โ”œโ”€โ”€ LICENSE
โ”œโ”€โ”€ bin/linecount.js      # the executable entry (thin)
โ”œโ”€โ”€ src/count.js          # the pure logic (easy to test)
โ””โ”€โ”€ test/count.test.js

Keeping the logic in src/ and a thin file in bin/ is the key design choice: pure functions are easy to test and reuse; the bin file only reads arguments, calls the function and prints.

Step 1: the logic

Node.js The counting logic

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.

Notice that naรฏve cafรฉ has 10 characters but 12 bytes: counting bytes through Buffer.byteLength is the correct way to match what a file would report.

Step 2: the argument parsing

A CLI should parse options predictably. Node ships util.parseArgs, so no dependency is needed (fewer dependencies means less to install and audit).

Node.js Parse arguments with node:util

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.

Step 3: the executable

A file becomes a command through two things: a shebang on the first line and the bin field in package.json.

JavaScript
#!/usr/bin/env node
import { readFileSync } from 'node:fs';
import { parseArgs } from 'node:util';
import { count, format } from '../src/count.js';

const { values, positionals } = parseArgs({
  allowPositionals: true,
  options: { lines: { type: 'boolean', short: 'l' }, words: { type: 'boolean', short: 'w' }, help: { type: 'boolean', short: 'h' } },
});

if (values.help || positionals.length === 0) {
  console.log('Usage: linecount [-l] [-w] <file...>');
  process.exit(values.help ? 0 : 2);
}

let failed = false;
for (const file of positionals) {
  try {
    const result = count(readFileSync(file, 'utf8'));
    if (values.lines) console.log(result.lines, file);
    else if (values.words) console.log(result.words, file);
    else console.log(format(result, file));
  } catch (error) {
    console.error(`linecount: ${file}: ${error.code ?? error.message}`);
    failed = true;
  }
}
process.exit(failed ? 1 : 0);

Good CLI manners are built into that script: usage text on --help, exit code 2 for misuse, exit code 1 when any file fails, errors on stderr (so pipes carry only results), and a clear message instead of a stack trace.

When the package is installed, the manager creates a link named after the bin key in node_modules/.bin (or a global bin folder for -g). On Unix the file also needs the executable bit, which npm sets for bin files on install; on Windows it generates small .cmd wrappers.

Step 4: the manifest

JSON
{
  "name": "linecount",
  "version": "1.0.0",
  "description": "Count lines, words and bytes in text files",
  "license": "MIT",
  "type": "module",
  "bin": { "linecount": "./bin/linecount.js" },
  "exports": { ".": "./src/count.js", "./package.json": "./package.json" },
  "files": ["bin", "src"],
  "engines": { "node": ">=20" },
  "scripts": {
    "test": "node --test",
    "prepublishOnly": "npm test"
  },
  "keywords": ["cli", "wc", "lines", "words"]
}

Three details: bin can also be a plain string ("bin": "./bin/linecount.js") in which case the command takes the package name; files leaves out test/ so users do not download your tests; and there are no dependencies, which keeps npx linecount fast.

Step 5: test it

Node has a built-in test runner, so tests need no framework. The next example writes the CLI into a temporary folder and runs it as a real child process, exactly like a user would.

Node.js Run the CLI as a child process

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 assertions that matter for a CLI are the exit codes and what goes to stdout versus stderr. In your own project, put these checks in test/ with node:test and assert.

Step 6: check the tarball

On your machine, before publishing:

Terminal
npm test
npm pack --dry-run

You should see exactly: package.json, README.md, LICENSE, bin/linecount.js, src/count.js. If test/ or .env appears, fix files. Then try the tarball like a real user, without publishing:

Terminal
npm pack                                  # creates linecount-1.0.0.tgz
cd $(mktemp -d)
npm install /path/to/linecount-1.0.0.tgz
npx linecount --help

This stand-in checks the same things automatically: that every bin target exists in the file list, that it starts with a shebang, and that nothing from a deny list is shipped.

Node.js Stand-in: pre-publish checks for a CLI package

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.

Step 7: publish and verify

Terminal
npm login
npm publish --dry-run     # last look
npm publish               # first publish (add --access public if scoped)
npx linecount@latest --help

Use npx linecount@latest in an empty folder to check what a stranger gets. Then apply the habits from this chapter: tag the commit (git tag v1.0.0), turn on two-factor authentication for publish, and for the next release use npm version patch (see versioning and the release workflow).

Ideas to extend it: add a --json flag, read from stdin when no file is given, add a bin alias, publish a 2.0.0-beta.1 under the next tag, or switch to pnpm and compare the published tarball with pnpm pack.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which two things make a file runnable as a command after install?

    The shebang tells the OS to run it with Node, and bin tells the package manager which command name to link to the file.
  2. 2. Why should a CLI print errors to stderr and use non-zero exit codes?

    Pipelines and CI depend on exit codes, and stdout should carry only the program's real output.
  3. 3. Why keep the counting logic in src/ and not directly in the bin file?

    Separating logic from argument parsing and printing makes unit tests simple.
  4. 4. What does npm pack --dry-run protect you from?

    It lists the exact files that would be in the tarball, so you can catch stray tests, secrets or missing build output.

Summary

  • A publishable CLI is a thin bin script, pure logic in src/, a manifest with bin, files, exports and engines, and no unnecessary dependencies.
  • Use util.parseArgs, exit codes and stderr for well-behaved commands.
  • Test as a child process and check exit codes and output streams.
  • Always inspect the tarball with npm pack --dry-run, install it from a .tgz in an empty folder, then publish and verify with npx.

Next: Project: A Mini Dependency Resolver