rhythmjs

Search documentation

Search guides, the tutorial and every package.

On this page

Run a cli#

toCliHandler(app, io?) from @rhythmjs/cli/run takes a RhythmCli, or a Rhythm host app that mounts one, and returns (argv: string[]) => Promise<number>. It builds the cli context from the arguments, runs the pipeline once, and resolves with the exit code. Output goes to process.stdout and process.stderr unless you pass your own { stdout, stderr } writers. Nothing calls process.exit() for you; set process.exitCode and close what you opened.

TypeScript
#!/usr/bin/env bun
import { toCliHandler } from "@rhythmjs/cli/run";
import { cli } from "./cli";

process.exitCode = await toCliHandler(cli)(Bun.argv.slice(2));

An unmatched command reports error: unknown command 'x' (or no command given) with exit code 2. A thrown error is reported as an error line with exit code 1.

Run a host app#

When the cli needs startup values, mount it into a Rhythm app and run the app. Stop the app when the command finishes so its cleanups run.

TypeScript
import { Rhythm, decorate, mount } from "@rhythmjs/rhythm";

const app = new Rhythm({ name: "tool" })
  .register(
    decorate(async () => ({ db: await createDb() })),
    (ctx) => ctx.db.close(),
  )
  .use(mount(cli));

try {
  process.exitCode = await toCliHandler(app)(Bun.argv.slice(2));
} finally {
  await app.stop();
}

Capture output#

Pass writers to collect output instead of printing it. This is also what @rhythmjs/testing/cli does for you.

TypeScript
let stdout = "";
const io = { stdout: { write: (text: string) => void (stdout += text) }, stderr: process.stderr };

const code = await toCliHandler(cli, io)(["deploy", "staging"]);

Prompt I/O#

withPrompt() wires the prompt surface to Bun directly: questions write to process.stdout, and answers are read from Bun's async-iterable console (one await per line, no readline interface). The input is closed when the command finishes. See interactive prompts.