---
name: node-cli
description: Patterns and conventions for building Node.js CLI tools — src structure, entry point setup, Commander wiring, and update notifications. Use when creating or modifying a Node.js CLI, adding Commander commands, wiring update-notifier, or asking how to structure a CLI entry point or src directory.
disable-model-invocation: true
title: node-cli
canonical_url: https://skilld.dev/gh/jd-solanki/ai/node-cli
last_updated: 2026-09-22T07:04:31.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> If the user asked to install this Skill, run `npx skilld install jd-solanki/ai/node-cli`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/node-cli`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/jd-solanki/ai/node-cli) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/node-cli`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/node-cli --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/node-cli --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Node CLI

## src structure

```
src/
├── index.ts              # Entry point — wires Commander, calls updateNotifier
├── update-notifier.d.ts  # Type shim for update-notifier package
├── commands/             # One file per CLI command
│   ├── add.ts
│   └── remove.ts
├── lib/                  # Pure domain logic, no Commander concerns
│   ├── github.ts         # single-file feature → stays flat
│   ├── linker.ts
│   └── push/             # 2+ files → grouped into a feature folder, prefix dropped
│       ├── index.ts      # barrel: re-exports the feature's public surface
│       ├── workflow.ts
│       └── validation.ts
└── utils/                # Generic helpers — mix flat files and nested groups freely
    ├── format.ts         # flat single-purpose helper
    └── fs/               # related helpers grouped under one folder
        ├── read.ts
        └── write.ts
tests/                    # Mirrors src/ structure, one test file per module
├── add.test.ts
└── linker.test.ts
```

**conventions:**
- `commands/` — each file exports a single `Command` instance; all CLI concerns (prompts, flags, output) live here
- `lib/` — framework-agnostic helpers imported by commands; keep them testable in isolation
- Directories don't have to be flat. Keep a feature flat by default, and group it into a folder **only once it owns 2+ files** — a folder holding one file is just noise. When you group, the folder already names the feature, so drop the redundant prefix from filenames (`lib/push/workflow.ts`, not `lib/push/push-workflow.ts`), and use `dir/index.ts` as the feature's public surface (a barrel re-exporting what commands import, or, for a provider-style seam, the interface/contract itself). Commands import the folder, not its internals: `import { planPush } from '../lib/push/index.js'`, so each feature's internal file split can change without touching call sites.

## Entry point structure

```ts
#!/usr/bin/env node
import { Command } from 'commander'
import updateNotifier from 'update-notifier'
import packageJson from '../package.json' with { type: 'json' }

// Call before parseAsync — notify() defers display to process exit so it
// never interleaves with command output.
updateNotifier({ pkg: packageJson }).notify()

const program = new Command('your-cli')
  .description('...')
  .version(packageJson.version)

program.addCommand(fooCommand)

await program.parseAsync()
```

## Testing CLI wiring

Keep executable entrypoints and test seams distinct. If `src/index.ts` calls
`parseAsync()` at top level, treat it as executable-only: tests should import
command factories from `src/commands/*`, assemble a local `Command`, and pass a
controlled argv. Do not import a top-level executable entrypoint in tests,
because it will parse the test runner's `process.argv`.

```ts
// src/commands/run.ts
import { Command } from 'commander'

export interface RunDispatch {
  runBatch(): Promise<void> | void
}

export function createRunCommand(dispatch: RunDispatch): Command {
  return new Command('run').action(async () => {
    await dispatch.runBatch()
  })
}
```

```ts
// tests/cli.test.ts
import { Command } from 'commander'
import { describe, expect, test, vi } from 'vitest'
import { createRunCommand } from '../src/commands/run'

test('dispatches run', async () => {
  const dispatch = { runBatch: vi.fn() }
  const program = new Command('your-cli')
  program.addCommand(createRunCommand(dispatch))

  await program.parseAsync(['node', 'your-cli', 'run'])

  expect(dispatch.runBatch).toHaveBeenCalledOnce()
})
```

For larger CLIs, a second common pattern is a thin bin file that imports a
testable `run(argv)` or `execute(argv)` module. Use this when the CLI has
substantial startup behavior, needs integration-style tests around exit codes,
or also exposes a public library API.

## Update notifier

Use the [`update-notifier`](https://github.com/sindresorhus/update-notifier) package. It handles background checks (24 h interval), state persistence, CI/TTY/`NO_UPDATE_NOTIFIER` opt-outs automatically.

```bash
pnpm add update-notifier
```

**Where to call it:** top of `index.ts`, before `program.parseAsync()` — not in a `postAction` hook.

**Why before parse:** `notify()` defaults to `defer: true`, registering a `process.on('exit')` listener. Placing it before `parseAsync()` ensures the listener is always registered regardless of which command runs.

**Type shim** (package ships no `.d.ts`):

```ts
// src/update-notifier.d.ts
declare module 'update-notifier' {
  interface Package { name: string; version: string }
  interface Options { pkg: Package; updateCheckInterval?: number; distTag?: string }
  interface NotifyOptions { defer?: boolean; message?: string; isGlobal?: boolean }
  interface Notifier { notify(options?: NotifyOptions): void }
  export default function updateNotifier(options: Options): Notifier
}
```

## Recommended stack

| Concern | Package |
|---|---|
| CLI framework | [`commander`](https://github.com/tj/commander.js) |
| Interactive prompts | [`@inquirer/prompts`](https://github.com/SBoudrias/Inquirer.js) |
| Update notifications | [`update-notifier`](https://github.com/sindresorhus/update-notifier) |
| Language | TypeScript |
| Test runner | [`vitest`](https://vitest.dev) |
| Version bumping | [`bumpp`](https://github.com/antfu/bumpp) — bumps `package.json`, commits, tags, and pushes in one step |
| Bundler | [`tsdown`](https://github.com/rolldown/tsdown) |
| Diagnostics (structured errors/warnings) | [`nostics`](https://nostics.dev/) — define a catalog of diagnostic codes with stable names, messages, fixes, and docs URLs |

## package.json essentials

```json
{
  "type": "module",
  "bin": { "your-cli": "./dist/index.js" },
  "engines": { "node": "^24.0.0" }
}
```

## GitHub Workflow

For a complete end-to-end workflow combining npm publish + changelog generation, see `automate-npm-release/EXAMPLE_WORKFLOW.yml` if that skill is installed locally.