Skip to content

Prompts

The @clack/prompts package provides a collection of pre-built, high-level prompts that make it easy to create interactive command-line interfaces. It builds on top of the core package to provide a more developer-friendly experience.

  • Pre-built prompts: Ready-to-use prompt components
  • Consistent styling: Unified look and feel across all prompts
  • Type-safe: Full TypeScript support
  • Customizable: Easy to extend and modify
  • AbortController support: Cancel prompts programmatically
  • Custom I/O streams: Use custom input/output streams
Terminal window
npm install @clack/prompts

The prompts package is designed to be intuitive and easy to use. Each prompt function returns a Promise that resolves to the user’s input.

For more detailed examples and advanced usage patterns, check out our examples guide and best practices.

All prompts share these common options:

The withGuide option (boolean option, not a separate API) turns Clack’s border/guide lines on or off. Every prompt accepts it alongside message and friends. You can set it globally with updateSettings or override it per call.

import {
const text: (opts: TextOptions) => Promise<string | symbol>

The text prompt accepts a single line of text.

@seehttps://bomb.sh/docs/clack/packages/prompts/#text-input

@example

import { text } from '@clack/prompts';
const name = await text({
message: 'What is your name?',
placeholder: 'John Doe',
validate: (value) => {
if (!value || value.length < 2) return 'Name must be at least 2 characters';
return undefined;
},
});

text
,
function updateSettings(updates: ClackSettings): void
updateSettings
} from '@clack/prompts';
// Disable globally
function updateSettings(updates: ClackSettings): void
updateSettings
({
ClackSettings.withGuide?: boolean
withGuide
: false });
// Or per-prompt
const
const name: string | symbol
name
= await
function text(opts: TextOptions): Promise<string | symbol>

The text prompt accepts a single line of text.

@seehttps://bomb.sh/docs/clack/packages/prompts/#text-input

@example

import { text } from '@clack/prompts';
const name = await text({
message: 'What is your name?',
placeholder: 'John Doe',
validate: (value) => {
if (!value || value.length < 2) return 'Name must be at least 2 characters';
return undefined;
},
});

text
({
TextOptions.message: string

The prompt message or question shown to the user above the input.

message
: 'What is your name?',
CommonOptions.withGuide?: boolean
withGuide
: false, // Disable guide lines for this prompt
});

Session helpers use the same option on their second argument: intro(title, { withGuide: false }), outro(message, { withGuide: false }), and cancel(message, { withGuide: false }).

autocomplete and multiselect respect withGuide: false per prompt (as of v1.2.0), matching other prompts.

All prompts accept a signal option for programmatic cancellation:

import {
const confirm: (opts: ConfirmOptions) => Promise<boolean | symbol>

The confirm prompt accepts a yes or no choice, returning a boolean value corresponding to the user's selection.

@seehttps://bomb.sh/docs/clack/packages/prompts/#confirmation

@example

import { confirm } from '@clack/prompts';
const shouldProceed = await confirm({
message: 'Do you want to continue?',
});

confirm
} from '@clack/prompts';
// Auto-cancel after 10 seconds
const
const shouldContinue: boolean | symbol
shouldContinue
= await
function confirm(opts: ConfirmOptions): Promise<boolean | symbol>

The confirm prompt accepts a yes or no choice, returning a boolean value corresponding to the user's selection.

@seehttps://bomb.sh/docs/clack/packages/prompts/#confirmation

@example

import { confirm } from '@clack/prompts';
const shouldProceed = await confirm({
message: 'Do you want to continue?',
});

confirm
({
ConfirmOptions.message: string

The message or question shown to the user above the input.

message
: 'This will self-destruct in 10 seconds',
CommonOptions.signal?: AbortSignal
signal
:
var AbortSignal: {
new (): AbortSignal;
prototype: AbortSignal;
abort(reason?: any): AbortSignal;
any(signals: AbortSignal[]): AbortSignal;
timeout(milliseconds: number): AbortSignal;
}
AbortSignal
.
function timeout(milliseconds: number): AbortSignal
timeout
(10000),
});

You can provide custom input and output streams for all prompts:

import {
class Writable

@sincev0.9.4

Writable
,
class Readable

@sincev0.9.4

Readable
} from 'node:stream';
import {
const text: (opts: TextOptions) => Promise<string | symbol>

The text prompt accepts a single line of text.

@seehttps://bomb.sh/docs/clack/packages/prompts/#text-input

@example

import { text } from '@clack/prompts';
const name = await text({
message: 'What is your name?',
placeholder: 'John Doe',
validate: (value) => {
if (!value || value.length < 2) return 'Name must be at least 2 characters';
return undefined;
},
});

text
} from '@clack/prompts';
declare const
const customInput: Readable
customInput
:
class Readable

@sincev0.9.4

Readable
;
declare const
const customOutput: Writable
customOutput
:
class Writable

@sincev0.9.4

Writable
;
const
const name: string | symbol
name
= await
function text(opts: TextOptions): Promise<string | symbol>

The text prompt accepts a single line of text.

@seehttps://bomb.sh/docs/clack/packages/prompts/#text-input

@example

import { text } from '@clack/prompts';
const name = await text({
message: 'What is your name?',
placeholder: 'John Doe',
validate: (value) => {
if (!value || value.length < 2) return 'Name must be at least 2 characters';
return undefined;
},
});

text
({
TextOptions.message: string

The prompt message or question shown to the user above the input.

message
: 'What is your name?',
CommonOptions.input?: Readable
input
:
const customInput: Readable
customInput
,
CommonOptions.output?: Writable
output
:
const customOutput: Writable
customOutput
,
});

The text prompt accepts a single line of text.

import {
const text: (opts: TextOptions) => Promise<string | symbol>

The text prompt accepts a single line of text.

@seehttps://bomb.sh/docs/clack/packages/prompts/#text-input

@example

import { text } from '@clack/prompts';
const name = await text({
message: 'What is your name?',
placeholder: 'John Doe',
validate: (value) => {
if (!value || value.length < 2) return 'Name must be at least 2 characters';
return undefined;
},
});

text
} from '@clack/prompts';
const
const name: string | symbol
name
= await
function text(opts: TextOptions): Promise<string | symbol>

The text prompt accepts a single line of text.

@seehttps://bomb.sh/docs/clack/packages/prompts/#text-input

@example

import { text } from '@clack/prompts';
const name = await text({
message: 'What is your name?',
placeholder: 'John Doe',
validate: (value) => {
if (!value || value.length < 2) return 'Name must be at least 2 characters';
return undefined;
},
});

text
({
TextOptions.message: string

The prompt message or question shown to the user above the input.

message
: 'What is your name?',
TextOptions.placeholder?: string

A visual hint shown when the field has no content.

placeholder
: 'John Doe',
TextOptions.validate?: Validate<string>

A function or a Standard Schema that validates user input. If a custom function is given, you should return a string or Error to show as a validation error, or undefined to accept the result.

validate
: (
value: string | undefined
value
) => {
if (!
value: string | undefined
value
||
value: string
value
.
String.length: number

Returns the length of a String object.

length
< 2) return 'Name must be at least 2 characters';
return
var undefined
undefined
;
},
});

  What is your name?
  John Doe

Options:

  • message: The prompt message shown to the user above the input.
  • placeholder: A visual hint shown when the field has no content.
  • defaultValue: A fallback value returned when the user provides nothing (empty input).
  • initialValue: The starting value shown when the prompt first renders. Users can edit this value before submitting.
  • validate: A function or a Standard Schema that validates user input. If a custom function is given, you should return a string or Error to show as a validation error, or undefined to accept the result..
  • All Common Options

Behaves like the text component, but the input is masked.

import {
const password: (opts: PasswordOptions) => Promise<string | symbol>

The password prompt behaves like the

text

prompt, but the input is masked.

@seehttps://bomb.sh/docs/clack/packages/prompts/#password-input

@example

import { password } from '@clack/prompts';
const result = await password({
message: 'Enter your password',
});

password
} from '@clack/prompts';
const
const secret: string | symbol
secret
= await
function password(opts: PasswordOptions): Promise<string | symbol>

The password prompt behaves like the

text

prompt, but the input is masked.

@seehttps://bomb.sh/docs/clack/packages/prompts/#password-input

@example

import { password } from '@clack/prompts';
const result = await password({
message: 'Enter your password',
});

password
({
PasswordOptions.message: string

The prompt message or question shown to the user above the input.

message
: 'What is your password?',
PasswordOptions.mask?: string

Character to use for masking input.

@default▪/•

mask
: '*',
PasswordOptions.clearOnError?: boolean

When enabled it causes the input to be cleared if/when validation fails.

@defaultfalse

clearOnError
: true, // Clear input when validation fails
PasswordOptions.validate?: Validate<string>

A function or a Standard Schema that validates user input. If a custom function is given, you should return a string or Error to show as a validation error, or undefined to accept the result.

validate
: (
value: string | undefined
value
) => {
if (!
value: string | undefined
value
||
value: string
value
.
String.length: number

Returns the length of a String object.

length
< 8) return 'Your password must be at least 8 characters';
if (!/[A-Z]/.
RegExp.test(string: string): boolean

Returns a Boolean value that indicates whether or not a pattern exists in a searched string.

@paramstring String on which to perform the search.

test
(
value: string
value
)) return 'Your password must be least contain 1 uppercase letter';
if (!/[0-9]/.
RegExp.test(string: string): boolean

Returns a Boolean value that indicates whether or not a pattern exists in a searched string.

@paramstring String on which to perform the search.

test
(
value: string
value
)) return 'Your password must be least contain 1 number';
if (!/[*?!@&]/.
RegExp.test(string: string): boolean

Returns a Boolean value that indicates whether or not a pattern exists in a searched string.

@paramstring String on which to perform the search.

test
(
value: string
value
)) return 'Your password must be least contain 1 special characters (*?!@&)';
return
var undefined
undefined
;
},
});

  What is your password?
  *****_

Options:

  • message: The prompt message or question shown to the user above the input.
  • mask: Character to use for masking input. Default: '▪/•'.
  • validate: A function or a Standard Schema that validates user input. If a custom function is given, you should return a string or Error to show as a validation error, or undefined to accept the result.
  • clearOnError: When enabled it causes the input to be cleared if/when validation fails. Default: false.
  • All Common Options

Common options (withGuide, signal, input, output) are also supported.

The multi-line component accepts multiple lines of text input. By default, pressing Enter twice submits the input.

import {
const multiline: (opts: MultiLineOptions) => Promise<string | symbol>

The multi-line prompt accepts multiple lines of text input. By default, pressing Enter twice submits the input.

@seehttps://bomb.sh/docs/clack/packages/prompts/#multi-line-text

@example

import { multiline } from '@clack/prompts';
const bio = await multiline({
message: 'Enter your bio',
placeholder: 'Tell us about yourself...',
showSubmit: true,
});

multiline
} from '@clack/prompts';
const
const bio: string | symbol
bio
= await
function multiline(opts: MultiLineOptions): Promise<string | symbol>

The multi-line prompt accepts multiple lines of text input. By default, pressing Enter twice submits the input.

@seehttps://bomb.sh/docs/clack/packages/prompts/#multi-line-text

@example

import { multiline } from '@clack/prompts';
const bio = await multiline({
message: 'Enter your bio',
placeholder: 'Tell us about yourself...',
showSubmit: true,
});

multiline
({
TextOptions.message: string

The prompt message or question shown to the user above the input.

message
: 'Enter your bio',
TextOptions.placeholder?: string

A visual hint shown when the field has no content.

placeholder
: 'Tell us about yourself...',
MultiLineOptions.showSubmit?: boolean

When enabled it shows a [ submit ] button that can be focused with tab. By default, pressing Enter twice submits the input

@defaultfalse

showSubmit
: true,
});

 Enter your bio
  Tell us about yourself…

  [ submit ]

Options:

  • showSubmit: When enabled it shows a [ submit ] button that can be focused with tab. By default, pressing Enter twice submits the input. Default: false.
  • All Text Options
import {
const select: <Value>(opts: SelectOptions<Value>) => Promise<Value | symbol>
select
} from '@clack/prompts';
const
const framework: symbol | "next" | "astro" | "svelte"
framework
= await
select<"next" | "astro" | "svelte">(opts: SelectOptions<"next" | "astro" | "svelte">): Promise<symbol | "next" | "astro" | "svelte">
select
({
SelectOptions<Value>.message: string
message
: 'Pick a framework',
SelectOptions<"next" | "astro" | "svelte">.options: ({
value: "next";
label?: string;
hint?: string;
disabled?: boolean;
} | {
value: "astro";
label?: string;
hint?: string;
disabled?: boolean;
} | {
value: "svelte";
label?: string;
hint?: string;
disabled?: boolean;
})[]
options
: [
{
value: "next"

Internal data for this option.

value
: 'next',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'Next.js',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'React framework' },
{
value: "astro"

Internal data for this option.

value
: 'astro',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'Astro',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Content-focused' },
{
value: "svelte"

Internal data for this option.

value
: 'svelte',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'SvelteKit',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Compile-time framework' },
],
SelectOptions<Value>.maxItems?: number
maxItems
: 5, // Maximum number of items to display at once
});

  Pick a framework
   Next.js (React framework)
  ○ Astro (Content-focused)
  ○ SvelteKit (Compile-time framework)
import {
const select: <Value>(opts: SelectOptions<Value>) => Promise<Value | symbol>
select
} from '@clack/prompts';
const
const framework: symbol | {
framework: string;
language: string;
} | {
framework: null;
language: string;
}
framework
= await
select<{
framework: string;
language: string;
} | {
framework: null;
language: string;
}>(opts: SelectOptions<{
framework: string;
language: string;
} | {
framework: null;
language: string;
}>): Promise<...>
select
({
SelectOptions<Value>.message: string
message
: 'Pick a framework',
SelectOptions<{ framework: string; language: string; } | { framework: null; language: string; }>.options: ({
value: {
framework: string;
language: string;
};
label: string;
hint?: string;
disabled?: boolean;
} | {
value: {
framework: null;
language: string;
};
label: string;
hint?: string;
disabled?: boolean;
})[]
options
: [
{
value: {
framework: string;
language: string;
}
value
: {
framework: string
framework
: 'Next',
language: string
language
: 'React' },
label: string

Required. The user-facing text for this option.

label
: 'Next.js',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'React framework' },
{
value: {
framework: null;
language: string;
}
value
: {
framework: null
framework
: null,
language: string
language
: 'Astro' },
label: string

Required. The user-facing text for this option.

label
: 'Astro',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Content-focused' },
{
value: {
framework: string;
language: string;
}
value
: {
framework: string
framework
: 'Sveltekit',
language: string
language
: 'Svelte' },
label: string

Required. The user-facing text for this option.

label
: 'SvelteKit',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Compile-time framework' },
],
});

  Pick a framework
   Next.js (React framework)
  ○ Astro (Content-focused)
  ○ SvelteKit (Compile-time framework)

You can disable specific options to prevent selection:

import {
const select: <Value>(opts: SelectOptions<Value>) => Promise<Value | symbol>
select
} from '@clack/prompts';
const
const database: symbol | "postgres" | "mysql" | "mongodb" | "sqlite"
database
= await
select<"postgres" | "mysql" | "mongodb" | "sqlite">(opts: SelectOptions<"postgres" | "mysql" | "mongodb" | "sqlite">): Promise<symbol | "postgres" | "mysql" | "mongodb" | "sqlite">
select
({
SelectOptions<Value>.message: string
message
: 'Select a database',
SelectOptions<"postgres" | "mysql" | "mongodb" | "sqlite">.options: ({
value: "postgres";
label?: string;
hint?: string;
disabled?: boolean;
} | {
value: "mysql";
label?: string;
hint?: string;
disabled?: boolean;
} | {
value: "mongodb";
label?: string;
hint?: string;
disabled?: boolean;
} | {
...;
})[]
options
: [
{
value: "postgres"

Internal data for this option.

value
: 'postgres',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'PostgreSQL',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Recommended' },
{
value: "mysql"

Internal data for this option.

value
: 'mysql',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'MySQL' },
{
value: "mongodb"

Internal data for this option.

value
: 'mongodb',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'MongoDB',
disabled?: boolean

Whether this option is disabled. Disabled options are visible but cannot be selected.

By default, options are not disabled.

disabled
: true,
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Coming soon' },
{
value: "sqlite"

Internal data for this option.

value
: 'sqlite',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'SQLite' },
],
});

  Select a database
   PostgreSQL (Recommended)
  ○ MySQL
  MongoDB (Coming soon)
  ○ SQLite

Disabled options are displayed with strikethrough styling and cannot be selected.

import {
const multiselect: <Value>(opts: MultiSelectOptions<Value>) => Promise<Value[] | symbol>
multiselect
} from '@clack/prompts';
const
const framework: symbol | ({
framework: string;
language: string;
} | {
framework: null;
language: string;
})[]
framework
= await
multiselect<{
framework: string;
language: string;
} | {
framework: null;
language: string;
}>(opts: MultiSelectOptions<{
framework: string;
language: string;
} | {
framework: null;
language: string;
}>): Promise<...>
multiselect
({
MultiSelectOptions<Value>.message: string
message
: 'Pick a framework',
MultiSelectOptions<{ framework: string; language: string; } | { framework: null; language: string; }>.options: ({
value: {
framework: string;
language: string;
};
label: string;
hint?: string;
disabled?: boolean;
} | {
value: {
framework: null;
language: string;
};
label: string;
hint?: string;
disabled?: boolean;
})[]
options
: [
{
value: {
framework: string;
language: string;
}
value
: {
framework: string
framework
: 'Next',
language: string
language
: 'React' },
label: string

Required. The user-facing text for this option.

label
: 'Next.js',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'React framework' },
{
value: {
framework: null;
language: string;
}
value
: {
framework: null
framework
: null,
language: string
language
: 'Astro' },
label: string

Required. The user-facing text for this option.

label
: 'Astro',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Content-focused' },
{
value: {
framework: string;
language: string;
}
value
: {
framework: string
framework
: 'Sveltekit',
language: string
language
: 'Svelte' },
label: string

Required. The user-facing text for this option.

label
: 'SvelteKit',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Compile-time framework' },
],
MultiSelectOptions<Value>.maxItems?: number
maxItems
: 5, // Maximum number of items to display at once
});

  Pick a framework
   Next.js (React framework)
   Astro (Content-focused)
  ◻ SvelteKit (Compile-time framework)

selectKey shows each option with a visible key (the option value, typically one character). The user presses that key instead of moving a cursor with arrows—useful for compact yes/no/maybe menus or vim-style shortcuts.

import {
const selectKey: <Value extends string>(opts: SelectKeyOptions<Value>) => Promise<Value | symbol>
selectKey
,
function isCancel(value: unknown): value is symbol
isCancel
} from '@clack/prompts';
const
const action: string | symbol
action
= await
selectKey<string>(opts: SelectKeyOptions<string>): Promise<string | symbol>
selectKey
({
SelectKeyOptions<Value extends string>.message: string
message
: 'What next?',
SelectKeyOptions<string>.options: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}[]
options
: [
{
value: string

Internal data for this option.

value
: 'y',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'Continue' },
{
value: string

Internal data for this option.

value
: 'n',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'Stop' },
{
value: string

Internal data for this option.

value
: 's',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'Skip',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'optional' },
],
SelectKeyOptions<Value extends string>.caseSensitive?: boolean
caseSensitive
: false,
});
if (
function isCancel(value: unknown): value is symbol
isCancel
(
const action: string | symbol
action
)) {
var process: NodeJS.Process
process
.
NodeJS.Process.exit(code?: number | string | null): never

The process.exit() method instructs Node.js to terminate the process synchronously with an exit status of code. If code is omitted, exit uses either the 'success' code 0 or the value of process.exitCode if it has been set. Node.js will not terminate until all the 'exit' event listeners are called.

To exit with a 'failure' code:

import { exit } from 'node:process';
exit(1);

The shell that executed Node.js should see the exit code as 1.

Calling process.exit() will force the process to exit as quickly as possible even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations to process.stdout and process.stderr.

In most situations, it is not actually necessary to call process.exit() explicitly. The Node.js process will exit on its own if there is no additional work pending in the event loop. The process.exitCode property can be set to tell the process which exit code to use when the process exits gracefully.

For instance, the following example illustrates a misuse of the process.exit() method that could lead to data printed to stdout being truncated and lost:

import { exit } from 'node:process';
// This is an example of what *not* to do:
if (someConditionNotMet()) {
printUsageToStdout();
exit(1);
}

The reason this is problematic is because writes to process.stdout in Node.js are sometimes asynchronous and may occur over multiple ticks of the Node.js event loop. Calling process.exit(), however, forces the process to exit before those additional writes to stdout can be performed.

Rather than calling process.exit() directly, the code should set the process.exitCode and allow the process to exit naturally by avoiding scheduling any additional work for the event loop:

import process from 'node:process';
// How to properly set the exit code while letting
// the process exit gracefully.
if (someConditionNotMet()) {
printUsageToStdout();
process.exitCode = 1;
}

If it is necessary to terminate the Node.js process due to an error condition, throwing an uncaught error and allowing the process to terminate accordingly is safer than calling process.exit().

In Worker threads, this function stops the current thread rather than the current process.

@sincev0.1.13

@paramcode The exit code. For string type, only integer strings (e.g.,'1') are allowed.

exit
(0);
}

The autocomplete prompt combines text input with a searchable list of options. It’s perfect for when you have a large list of options and want to help users find what they’re looking for quickly.

import {
const autocomplete: <Value>(opts: AutocompleteOptions<Value>) => Promise<Value | symbol>

The autocomplete prompt combines a text input with a searchable list of options. It's perfect for when you have a large list of options and want to help users find what they're looking for quickly.

@seehttps://bomb.sh/docs/clack/packages/prompts/#autocomplete

@example

import { autocomplete } from '@clack/prompts';
const framework = await autocomplete({
message: 'Search for a framework',
options: [
{ value: 'next', label: 'Next.js', hint: 'React framework' },
{ value: 'astro', label: 'Astro', hint: 'Content-focused' },
{ value: 'svelte', label: 'SvelteKit', hint: 'Compile-time framework' },
{ value: 'remix', label: 'Remix', hint: 'Full stack framework' },
{ value: 'nuxt', label: 'Nuxt', hint: 'Vue framework' },
],
placeholder: 'Type to search...',
maxItems: 5,
});

autocomplete
} from '@clack/prompts';
const
const framework: symbol | "next" | "astro" | "svelte" | "remix" | "nuxt"
framework
= await
autocomplete<"next" | "astro" | "svelte" | "remix" | "nuxt">(opts: AutocompleteOptions<"next" | "astro" | "svelte" | "remix" | "nuxt">): Promise<symbol | "next" | "astro" | "svelte" | "remix" | "nuxt">

The autocomplete prompt combines a text input with a searchable list of options. It's perfect for when you have a large list of options and want to help users find what they're looking for quickly.

@seehttps://bomb.sh/docs/clack/packages/prompts/#autocomplete

@example

import { autocomplete } from '@clack/prompts';
const framework = await autocomplete({
message: 'Search for a framework',
options: [
{ value: 'next', label: 'Next.js', hint: 'React framework' },
{ value: 'astro', label: 'Astro', hint: 'Content-focused' },
{ value: 'svelte', label: 'SvelteKit', hint: 'Compile-time framework' },
{ value: 'remix', label: 'Remix', hint: 'Full stack framework' },
{ value: 'nuxt', label: 'Nuxt', hint: 'Vue framework' },
],
placeholder: 'Type to search...',
maxItems: 5,
});

autocomplete
({
AutocompleteSharedOptions<Value>.message: string

The message or question shown to the user above the input.

message
: 'Search for a framework',
AutocompleteSharedOptions<"next" | "astro" | "svelte" | "remix" | "nuxt">.options: ({
value: "next";
label?: string;
hint?: string;
disabled?: boolean;
} | {
value: "astro";
label?: string;
hint?: string;
disabled?: boolean;
} | {
value: "svelte";
label?: string;
hint?: string;
disabled?: boolean;
} | {
...;
} | {
...;
})[] | ((this: AutocompletePrompt<...>) => ({
value: "next";
label?: string;
hint?: string;
disabled?: boolean;
} | ... 3 more ... | {
...;
})[])

The options to present, or a function that returns the options to present allowing for custom search/filtering.

options
: [
{
value: "next"

Internal data for this option.

value
: 'next',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'Next.js',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'React framework' },
{
value: "astro"

Internal data for this option.

value
: 'astro',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'Astro',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Content-focused' },
{
value: "svelte"

Internal data for this option.

value
: 'svelte',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'SvelteKit',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Compile-time framework' },
{
value: "remix"

Internal data for this option.

value
: 'remix',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'Remix',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Full stack framework' },
{
value: "nuxt"

Internal data for this option.

value
: 'nuxt',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'Nuxt',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Vue framework' },
],
AutocompleteSharedOptions<Value>.placeholder?: string

Placeholder text displayed when the search field is empty. When set, pressing tab copies the placeholder into the input.

placeholder
: 'Type to search...',
AutocompleteSharedOptions<Value>.maxItems?: number

The maximum number of items/options to display in the autocomplete list at once.

maxItems
: 5,
});

 Search for a framework
  Search: n
  (2 matches)
  ● Next.js (React framework)
  ○ Nuxt (Vue framework)

Options:

  • message: The message or question shown to the user above the input.
  • options: The options to present, or a function that returns the options to present allowing for custom search/filtering. Learn more below.
  • maxItems: The maximum number of items/options to display in the autocomplete list at once.
  • placeholder: Placeholder text displayed when the search field is empty. When set, pressing tab copies the placeholder into the input.
  • validate: A function that validates user input. Return a string or Error to show as a validation error, or undefined to accept the result.
  • filter: Custom filter function to match options against the search input.
  • initialValue: The initially selected option from the list.
  • initialUserInput: The starting value shown in the users input box.
  • All Common Options

Instead of a static array, options can be a function whose this is the underlying AutocompletePrompt from @clack/core. The function runs again whenever the search text changes, so you can read this.userInput and return a new array in display order—for example closest / highest-score matches first (similar to fzf-style UIs). This pattern is what issue #467 discusses for custom ranking and libraries like Fuse.js.

The high-level autocomplete wrapper still applies its default filter (substring match on label, hint, and value) to whatever your getter returns. If you already narrow or rank items in the getter, disable that second pass with filter: (_search, _option) => true, or pass a custom (search, option) => boolean aligned with your getter.

options as a getter must be synchronous; there is no async API here—preload or sync work inside the function.

The same options shape is supported on autocompleteMultiselect.

import {
const autocomplete: <Value>(opts: AutocompleteOptions<Value>) => Promise<Value | symbol>

The autocomplete prompt combines a text input with a searchable list of options. It's perfect for when you have a large list of options and want to help users find what they're looking for quickly.

@seehttps://bomb.sh/docs/clack/packages/prompts/#autocomplete

@example

import { autocomplete } from '@clack/prompts';
const framework = await autocomplete({
message: 'Search for a framework',
options: [
{ value: 'next', label: 'Next.js', hint: 'React framework' },
{ value: 'astro', label: 'Astro', hint: 'Content-focused' },
{ value: 'svelte', label: 'SvelteKit', hint: 'Compile-time framework' },
{ value: 'remix', label: 'Remix', hint: 'Full stack framework' },
{ value: 'nuxt', label: 'Nuxt', hint: 'Vue framework' },
],
placeholder: 'Type to search...',
maxItems: 5,
});

autocomplete
} from '@clack/prompts';
import type {
class AutocompletePrompt<T extends OptionLike$1>
AutocompletePrompt
} from '@clack/core';
import type {
type Option<Value> = Value extends Primitive ? {
value: Value;
label?: string;
hint?: string;
disabled?: boolean;
} : {
value: Value;
label: string;
hint?: string;
disabled?: boolean;
}
Option
} from '@clack/prompts';
const
const pool: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}[]
pool
:
type Option<Value> = Value extends Primitive ? {
value: Value;
label?: string;
hint?: string;
disabled?: boolean;
} : {
value: Value;
label: string;
hint?: string;
disabled?: boolean;
}
Option
<string>[] = [
{
value: string

Internal data for this option.

value
: 'next',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'Next.js',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'React' },
{
value: string

Internal data for this option.

value
: 'nuxt',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'Nuxt',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Vue' },
{
value: string

Internal data for this option.

value
: 'nest',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'NestJS',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Node' },
];
function
function rankByQuery(query: string, items: Option<string>[]): Option<string>[]
rankByQuery
(
query: string
query
: string,
items: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}[]
items
:
type Option<Value> = Value extends Primitive ? {
value: Value;
label?: string;
hint?: string;
disabled?: boolean;
} : {
value: Value;
label: string;
hint?: string;
disabled?: boolean;
}
Option
<string>[]):
type Option<Value> = Value extends Primitive ? {
value: Value;
label?: string;
hint?: string;
disabled?: boolean;
} : {
value: Value;
label: string;
hint?: string;
disabled?: boolean;
}
Option
<string>[] {
const
const q: string
q
=
query: string
query
.
String.trim(): string

Removes the leading and trailing white space and line terminator characters from a string.

trim
().
String.toLowerCase(): string

Converts all the alphabetic characters in a string to lowercase.

toLowerCase
();
if (!
const q: string
q
) return [...
items: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}[]
items
];
return [...
items: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}[]
items
]
.
Array<{ value: string; label?: string; hint?: string; disabled?: boolean; }>.filter(predicate: (value: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}, index: number, array: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}[]) => unknown, thisArg?: any): {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}[] (+1 overload)

Returns the elements of an array that meet the condition specified in a callback function.

@parampredicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.

@paramthisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

filter
((
o: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}
o
) => {
const
const t: string
t
= `${
o: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}
o
.
label?: string | undefined

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
?? ''} ${
o: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}
o
.
hint?: string | undefined

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
?? ''} ${
o: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}
o
.
value: string

Internal data for this option.

value
}`.
String.toLowerCase(): string

Converts all the alphabetic characters in a string to lowercase.

toLowerCase
();
return
const t: string
t
.
String.includes(searchString: string, position?: number): boolean

Returns true if searchString appears as a substring of the result of converting this object to a String, at one or more positions that are greater than or equal to position; otherwise, returns false.

@paramsearchString search string

@paramposition If position is undefined, 0 is assumed, so as to search all of the String.

includes
(
const q: string
q
);
})
.
Array<{ value: string; label?: string; hint?: string; disabled?: boolean; }>.sort(compareFn?: ((a: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}, b: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}) => number) | undefined): {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}[]

Sorts an array in place. This method mutates the array and returns a reference to the same array.

@param

compareFn Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order.

[11,2,22,1].sort((a, b) => a - b)

sort
((
a: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}
a
,
b: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}
b
) => {
const
const la: string
la
= (
a: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}
a
.
label?: string | undefined

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
?? '').
String.toLowerCase(): string

Converts all the alphabetic characters in a string to lowercase.

toLowerCase
();
const
const lb: string
lb
= (
b: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}
b
.
label?: string | undefined

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
?? '').
String.toLowerCase(): string

Converts all the alphabetic characters in a string to lowercase.

toLowerCase
();
const
const sa: 0 | 1
sa
=
const la: string
la
.
String.startsWith(searchString: string, position?: number): boolean

Returns true if the sequence of elements of searchString converted to a String is the same as the corresponding elements of this object (converted to a String) starting at position. Otherwise returns false.

startsWith
(
const q: string
q
) ? 0 : 1;
const
const sb: 0 | 1
sb
=
const lb: string
lb
.
String.startsWith(searchString: string, position?: number): boolean

Returns true if the sequence of elements of searchString converted to a String is the same as the corresponding elements of this object (converted to a String) starting at position. Otherwise returns false.

startsWith
(
const q: string
q
) ? 0 : 1;
return
const sa: 0 | 1
sa
-
const sb: 0 | 1
sb
||
const la: string
la
.
String.localeCompare(that: string, locales?: Intl.LocalesArgument, options?: Intl.CollatorOptions): number (+2 overloads)

Determines whether two strings are equivalent in the current or specified locale.

@paramthat String to compare to target string

@paramlocales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.

@paramoptions An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.

localeCompare
(
const lb: string
lb
);
});
}
const
const picked: string | symbol
picked
= await
autocomplete<string>(opts: AutocompleteOptions<string>): Promise<string | symbol>

The autocomplete prompt combines a text input with a searchable list of options. It's perfect for when you have a large list of options and want to help users find what they're looking for quickly.

@seehttps://bomb.sh/docs/clack/packages/prompts/#autocomplete

@example

import { autocomplete } from '@clack/prompts';
const framework = await autocomplete({
message: 'Search for a framework',
options: [
{ value: 'next', label: 'Next.js', hint: 'React framework' },
{ value: 'astro', label: 'Astro', hint: 'Content-focused' },
{ value: 'svelte', label: 'SvelteKit', hint: 'Compile-time framework' },
{ value: 'remix', label: 'Remix', hint: 'Full stack framework' },
{ value: 'nuxt', label: 'Nuxt', hint: 'Vue framework' },
],
placeholder: 'Type to search...',
maxItems: 5,
});

autocomplete
({
AutocompleteSharedOptions<Value>.message: string

The message or question shown to the user above the input.

message
: 'Pick a framework',
AutocompleteSharedOptions<string>.options: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}[] | ((this: AutocompletePrompt<{
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}>) => {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}[])

The options to present, or a function that returns the options to present allowing for custom search/filtering.

options
(
this: AutocompletePrompt<{
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}>
this
:
class AutocompletePrompt<T extends OptionLike$1>
AutocompletePrompt
<
type Option<Value> = Value extends Primitive ? {
value: Value;
label?: string;
hint?: string;
disabled?: boolean;
} : {
value: Value;
label: string;
hint?: string;
disabled?: boolean;
}
Option
<string>>) {
return
function rankByQuery(query: string, items: Option<string>[]): Option<string>[]
rankByQuery
(this.
Prompt<string | string[]>.userInput: string
userInput
,
const pool: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}[]
pool
);
},
AutocompleteSharedOptions<string>.filter?: (search: string, option: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}) => boolean

Custom filter function to match options against the search input.

filter
: (
_search: string
_search
,
_option: {
value: string;
label?: string;
hint?: string;
disabled?: boolean;
}
_option
) => true,
});

The autocompleteMultiselect prompt combines the search functionality of autocomplete with the ability to select multiple options.

import {
const autocompleteMultiselect: <Value>(opts: AutocompleteMultiSelectOptions<Value>) => Promise<Value[] | symbol>

The autocompleteMultiselect prompt combines the search functionality of autocomplete with the ability to select multiple options.

@seehttps://bomb.sh/docs/clack/packages/prompts/#autocomplete-multiselect

@example

import { autocompleteMultiselect } from '@clack/prompts';
const frameworks = await autocompleteMultiselect({
message: 'Select frameworks',
options: [
{ value: 'next', label: 'Next.js', hint: 'React framework' },
{ value: 'astro', label: 'Astro', hint: 'Content-focused' },
{ value: 'svelte', label: 'SvelteKit', hint: 'Compile-time framework' },
{ value: 'remix', label: 'Remix', hint: 'Full stack framework' },
{ value: 'nuxt', label: 'Nuxt', hint: 'Vue framework' },
],
placeholder: 'Type to search...',
maxItems: 5,
});

autocompleteMultiselect
} from '@clack/prompts';
const
const frameworks: symbol | ("next" | "astro" | "svelte" | "remix" | "nuxt")[]
frameworks
= await
autocompleteMultiselect<"next" | "astro" | "svelte" | "remix" | "nuxt">(opts: AutocompleteMultiSelectOptions<"next" | "astro" | "svelte" | "remix" | "nuxt">): Promise<...>

The autocompleteMultiselect prompt combines the search functionality of autocomplete with the ability to select multiple options.

@seehttps://bomb.sh/docs/clack/packages/prompts/#autocomplete-multiselect

@example

import { autocompleteMultiselect } from '@clack/prompts';
const frameworks = await autocompleteMultiselect({
message: 'Select frameworks',
options: [
{ value: 'next', label: 'Next.js', hint: 'React framework' },
{ value: 'astro', label: 'Astro', hint: 'Content-focused' },
{ value: 'svelte', label: 'SvelteKit', hint: 'Compile-time framework' },
{ value: 'remix', label: 'Remix', hint: 'Full stack framework' },
{ value: 'nuxt', label: 'Nuxt', hint: 'Vue framework' },
],
placeholder: 'Type to search...',
maxItems: 5,
});

autocompleteMultiselect
({
AutocompleteSharedOptions<Value>.message: string

The message or question shown to the user above the input.

message
: 'Select frameworks',
AutocompleteSharedOptions<"next" | "astro" | "svelte" | "remix" | "nuxt">.options: ({
value: "next";
label?: string;
hint?: string;
disabled?: boolean;
} | {
value: "astro";
label?: string;
hint?: string;
disabled?: boolean;
} | {
value: "svelte";
label?: string;
hint?: string;
disabled?: boolean;
} | {
...;
} | {
...;
})[] | ((this: AutocompletePrompt<...>) => ({
value: "next";
label?: string;
hint?: string;
disabled?: boolean;
} | ... 3 more ... | {
...;
})[])

The options to present, or a function that returns the options to present allowing for custom search/filtering.

options
: [
{
value: "next"

Internal data for this option.

value
: 'next',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'Next.js',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'React framework' },
{
value: "astro"

Internal data for this option.

value
: 'astro',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'Astro',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Content-focused' },
{
value: "svelte"

Internal data for this option.

value
: 'svelte',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'SvelteKit',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Compile-time framework' },
{
value: "remix"

Internal data for this option.

value
: 'remix',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'Remix',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Full stack framework' },
{
value: "nuxt"

Internal data for this option.

value
: 'nuxt',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'Nuxt',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Vue framework' },
],
AutocompleteSharedOptions<Value>.placeholder?: string

Placeholder text displayed when the search field is empty. When set, pressing tab copies the placeholder into the input.

placeholder
: 'Type to search...',
AutocompleteSharedOptions<Value>.maxItems?: number

The maximum number of items/options to display in the autocomplete list at once.

maxItems
: 5, // Maximum number of items to display at once
});

 Select frameworks
  Search: n
  (2 matches)
  ◼ Next.js (React framework)
  ◻ Nuxt (Vue framework)

Options:

  • message: The prompt message or question shown to the user above the input.
  • options: The options to present, or a function that returns the options to present allowing for custom search/filtering. Learn more below.
  • maxItems: The maximum number of items/options to display in the autocomplete list at once.
  • placeholder: Placeholder text displayed when the search field is empty. When set, pressing tab copies the placeholder into the input.
  • validate: A function that validates user input. Return a string or Error to show as a validation error, or undefined to accept the result.
  • filter: Custom filter function to match options against the search input.
  • initialValues: The initially selected option(s) from the list.
  • required: When true at least one option must be selected (default: false).
  • All Common Options

The path prompt extends autocomplete to provide file and directory suggestions.

import {
const path: (opts: PathOptions) => Promise<string | symbol>

The path prompt extends autocomplete to provide file and directory suggestions.

@seehttps://bomb.sh/docs/clack/packages/prompts/#path-selection

@example

import { path } from '@clack/prompts';
const result = await path({
message: 'Select a file:',
root: process.cwd(),
directory: false,
});

path
} from '@clack/prompts';
const
const selectedPath: string | symbol
selectedPath
= await
function path(opts: PathOptions): Promise<string | symbol>

The path prompt extends autocomplete to provide file and directory suggestions.

@seehttps://bomb.sh/docs/clack/packages/prompts/#path-selection

@example

import { path } from '@clack/prompts';
const result = await path({
message: 'Select a file:',
root: process.cwd(),
directory: false,
});

path
({
PathOptions.message: string

The message or question shown to the user above the input.

message
: 'Select a file:',
PathOptions.root?: string

The starting directory for path suggestions (defaults to current working directory).

root
:
var process: NodeJS.Process
process
.
NodeJS.Process.cwd(): string

The process.cwd() method returns the current working directory of the Node.js process.

import { cwd } from 'node:process';
console.log(`Current directory: ${cwd()}`);

@sincev0.1.8

cwd
(), // Starting directory
PathOptions.directory?: boolean

When true only directories appear in suggestions while you navigate.

directory
: false, // Set to true to only show directories
});

  Select a file:
  Search: /Users/project/
  (3 matches)
  ● /Users/project/src
  ○ /Users/project/package.json
  ○ /Users/project/tsconfig.json

Options:

  • message: The message or question shown to the user above the input.
  • root: The starting directory for path suggestions (defaults to current working directory).
  • directory: When true only directories appear in suggestions while you navigate (v1.2.0 fixes for directory-only mode).
  • initialValue: The starting path shown when the prompt first renders, which users can edit before submitting. If not provided it will fall back to the given root, or the current working directory. In directory mode, if the initial value points to a directory that exists, pressing enter will submit the input instead of jumping to the first child (v1.2.0).
  • validate: A function that validates the given path. Return a string or Error to show as a validation error, or undefined to accept the result.
  • All Common Options

The date prompt provides an interactive date picker, allowing users to navigate between year, month, and day segments and increment/decrement values using keyboard controls.

import {
const date: (opts: DateOptions) => Promise<Date | symbol>
date
} from '@clack/prompts';
const
const birthday: symbol | Date
birthday
= await
function date(opts: DateOptions): Promise<Date | symbol>
date
({
DateOptions.message: string
message
: 'Pick your birthday',
DateOptions.minDate?: Date
minDate
: new
var Date: DateConstructor
new (value: number | string | Date) => Date (+3 overloads)
Date
('1900-01-01'),
DateOptions.initialValue?: Date
initialValue
: new
var Date: DateConstructor
new () => Date (+3 overloads)
Date
(),
DateOptions.maxDate?: Date
maxDate
: new
var Date: DateConstructor
new () => Date (+3 overloads)
Date
(),
});

Options:

  • message: The message or question shown to the user above the input.
  • format: The date format to use (default: based on locale).
  • locale: The BCP 47 language tag to use for formatting.
  • defaultValue: The default value returned when the user doesn’t select a date.
  • initialValue: The starting date shown when the prompt first renders. Users can edit this value before submitting.
  • minDate: The minimum allowed date for validation.
  • maxDate: The maximum allowed date for validation.
  • validate: A function or a Standard Schema that validates user input. If a custom function is given, you should return a string or Error to show as a validation error, or undefined to accept the result..
  • All Common Options

The confirm prompt accepts a yes or no choice, returning a boolean value corresponding to the user’s selection.

import {
const confirm: (opts: ConfirmOptions) => Promise<boolean | symbol>

The confirm prompt accepts a yes or no choice, returning a boolean value corresponding to the user's selection.

@seehttps://bomb.sh/docs/clack/packages/prompts/#confirmation

@example

import { confirm } from '@clack/prompts';
const shouldProceed = await confirm({
message: 'Do you want to continue?',
});

confirm
} from '@clack/prompts';
const
const shouldProceed: boolean | symbol
shouldProceed
= await
function confirm(opts: ConfirmOptions): Promise<boolean | symbol>

The confirm prompt accepts a yes or no choice, returning a boolean value corresponding to the user's selection.

@seehttps://bomb.sh/docs/clack/packages/prompts/#confirmation

@example

import { confirm } from '@clack/prompts';
const shouldProceed = await confirm({
message: 'Do you want to continue?',
});

confirm
({
ConfirmOptions.message: string

The message or question shown to the user above the input.

message
: 'Do you want to continue?',
});

 Do you want to continue?
   Yes / ○ No

Options:

  • message: The message or question shown to the user above the input.
  • active: The label to use for the active (true) option (default: Yes).
  • inactive: The label to use for the inactive (false) option (default: No).
  • initialValue: The initial selected value (true or false) (default: true).
  • vertical: Whether to render the options vertically instead of horizontally (default: false) (v1.0.1+).
  • All Common Options

The groupMultiselect prompt extends the multiselect prompt to allow arranging distinct Multi-Selects, whilst keeping all of them interactive.

import {
const groupMultiselect: <Value>(opts: GroupMultiSelectOptions<Value>) => Promise<Value[] | symbol>

The groupMultiselect prompt extends the

multiselect

prompt to allow arranging distinct Multi-Selects, whilst keeping all of them interactive.

@seehttps://bomb.sh/docs/clack/packages/prompts/#group-multiselect

@example

import { groupMultiselect } from '@clack/prompts';
const result = await groupMultiselect({
message: 'Define your project',
options: {
'Testing': [
{ value: 'Jest', hint: 'JavaScript testing framework' },
{ value: 'Playwright', hint: 'End-to-end testing' },
],
'Language': [
{ value: 'js', label: 'JavaScript', hint: 'Dynamic typing' },
{ value: 'ts', label: 'TypeScript', hint: 'Static typing' },
],
},
});

@paramopts The options for the group multiselect prompt

groupMultiselect
} from '@clack/prompts';
const
const projectOptions: symbol | ("Jest" | "Playwright" | "Vitest" | "js" | "ts" | "coffee" | "Prettier" | "ESLint" | "Biome.js")[]
projectOptions
= await
groupMultiselect<"Jest" | "Playwright" | "Vitest" | "js" | "ts" | "coffee" | "Prettier" | "ESLint" | "Biome.js">(opts: GroupMultiSelectOptions<"Jest" | "Playwright" | "Vitest" | "js" | "ts" | "coffee" | "Prettier" | "ESLint" | "Biome.js">): Promise<...>

The groupMultiselect prompt extends the

multiselect

prompt to allow arranging distinct Multi-Selects, whilst keeping all of them interactive.

@seehttps://bomb.sh/docs/clack/packages/prompts/#group-multiselect

@example

import { groupMultiselect } from '@clack/prompts';
const result = await groupMultiselect({
message: 'Define your project',
options: {
'Testing': [
{ value: 'Jest', hint: 'JavaScript testing framework' },
{ value: 'Playwright', hint: 'End-to-end testing' },
],
'Language': [
{ value: 'js', label: 'JavaScript', hint: 'Dynamic typing' },
{ value: 'ts', label: 'TypeScript', hint: 'Static typing' },
],
},
});

@paramopts The options for the group multiselect prompt

groupMultiselect
({
GroupMultiSelectOptions<Value>.message: string

The message or question shown to the user above the input.

message
: 'Define your project',
GroupMultiSelectOptions<"Jest" | "Playwright" | "Vitest" | "js" | "ts" | "coffee" | "Prettier" | "ESLint" | "Biome.js">.options: Record<string, ({
value: "Jest";
label?: string;
hint?: string;
disabled?: boolean;
} | {
value: "Playwright";
label?: string;
hint?: string;
disabled?: boolean;
} | {
value: "Vitest";
label?: string;
hint?: string;
disabled?: boolean;
} | ... 5 more ... | {
...;
})[]>

Grouped options to display. Each key is a group label, and each value is an array of options.

options
: {
'Testing': [
{
value: "Jest"

Internal data for this option.

value
: 'Jest',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'JavaScript testing framework' },
{
value: "Playwright"

Internal data for this option.

value
: 'Playwright',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'End-to-end testing' },
{
value: "Vitest"

Internal data for this option.

value
: 'Vitest',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Vite-native testing' },
],
'Language': [{
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: "Javascript",
value: "js"

Internal data for this option.

value
: 'js',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Dynamic typing'
}, {
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'TypeScript',
value: "ts"

Internal data for this option.

value
: 'ts',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Static typing'
}, {
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: "CoffeeScript",
value: "coffee"

Internal data for this option.

value
: 'coffee',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'JavaScript with Ruby-like syntax'
}],
'Code quality': [
{
value: "Prettier"

Internal data for this option.

value
: 'Prettier',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Code formatter' },
{
value: "ESLint"

Internal data for this option.

value
: 'ESLint',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Linter' },
{
value: "Biome.js"

Internal data for this option.

value
: 'Biome.js',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Formatter and linter' },
],
},
GroupMultiSelectOptions<Value>.groupSpacing?: number

Number of blank lines between groups.

@default0

groupSpacing
: 1, // Add one new line between each group
GroupMultiSelectOptions<Value>.selectableGroups?: boolean

Whether entire groups can be selected at once.

@defaulttrue

selectableGroups
: false, // Disable selection of top-level groups
});

 Define your project
   Testing
 Jest (JavaScript testing framework)
 Playwright (End-to-end testing)
 Vitest (Vite-native testing)

   Language
 Javascript (Dynamic typing)
 TypeScript (Static typing)
 CoffeeScript (JavaScript with Ruby-like syntax)

  ◻ Code quality
  │ ◻ Prettier (Code formatter)
  │ ◻ ESLint (Linter)
 Biome.js (Formatter and linter)

Options:

  • message: The message or question shown to the user above the input.
  • options: Grouped options to display. Each key is a group label, and each value is an array of options.
  • initialValues: The initially selected option(s).
  • maxItems: The maximum number of items/options to display at once.
  • required: When true at least one option must be selected (default: true).
  • cursorAt: The value the cursor should be positioned at initially.
  • selectableGroups: Whether entire groups can be selected at once (default: true).
  • groupSpacing: Number of blank lines between groups (default: 0).
  • All Common Options

The group utility provides a consistent way to combine a series of prompts, combining each answer into one object. Each prompt receives the results of all previously completed prompts, and are executed sequentially.

import {
const group: <T>(prompts: PromptGroup<T>, opts?: PromptGroupOptions<T>) => Promise<{ [P in keyof PromptGroupAwaitedReturn<...>]: PromptGroupAwaitedReturn<...>[P]; }>

The group utility provides a consistent way to combine a series of prompts, combining each answer into one object. Each prompt receives the results of all previously completed prompts, and are displayed sequentially.

@seehttps://bomb.sh/docs/clack/packages/prompts/#group

@example

import { group, text, password } from '@clack/prompts';
const account = await group({
email: () => text({
message: 'What is your email address?',
}),
username: ({ results }) => text({
message: 'What is your username?',
placeholder: results.email?.replace(/@.+$/, '').toLowerCase() ?? '',
}),
password: () => password({
message: 'Define your password',
}),
});

group
,
const text: (opts: TextOptions) => Promise<string | symbol>

The text prompt accepts a single line of text.

@seehttps://bomb.sh/docs/clack/packages/prompts/#text-input

@example

import { text } from '@clack/prompts';
const name = await text({
message: 'What is your name?',
placeholder: 'John Doe',
validate: (value) => {
if (!value || value.length < 2) return 'Name must be at least 2 characters';
return undefined;
},
});

text
,
const password: (opts: PasswordOptions) => Promise<string | symbol>

The password prompt behaves like the

text

prompt, but the input is masked.

@seehttps://bomb.sh/docs/clack/packages/prompts/#password-input

@example

import { password } from '@clack/prompts';
const result = await password({
message: 'Enter your password',
});

password
} from '@clack/prompts';
const
const account: {
email: string;
username: unknown;
password: string;
}
account
= await
group<{
email: string | symbol;
username: unknown;
password: string | symbol;
}>(prompts: PromptGroup<{
email: string | symbol;
username: unknown;
password: string | symbol;
}>, opts?: PromptGroupOptions<{
email: string | symbol;
username: unknown;
password: string | symbol;
}> | undefined): Promise<...>

The group utility provides a consistent way to combine a series of prompts, combining each answer into one object. Each prompt receives the results of all previously completed prompts, and are displayed sequentially.

@seehttps://bomb.sh/docs/clack/packages/prompts/#group

@example

import { group, text, password } from '@clack/prompts';
const account = await group({
email: () => text({
message: 'What is your email address?',
}),
username: ({ results }) => text({
message: 'What is your username?',
placeholder: results.email?.replace(/@.+$/, '').toLowerCase() ?? '',
}),
password: () => password({
message: 'Define your password',
}),
});

group
({
email: (opts: {
results: {
username?: unknown;
password?: string;
};
}) => Promise<string | symbol | undefined> | undefined
email
: () =>
function text(opts: TextOptions): Promise<string | symbol>

The text prompt accepts a single line of text.

@seehttps://bomb.sh/docs/clack/packages/prompts/#text-input

@example

import { text } from '@clack/prompts';
const name = await text({
message: 'What is your name?',
placeholder: 'John Doe',
validate: (value) => {
if (!value || value.length < 2) return 'Name must be at least 2 characters';
return undefined;
},
});

text
({
TextOptions.message: string

The prompt message or question shown to the user above the input.

message
: 'What is your email address?',
TextOptions.validate?: Validate<string>

A function or a Standard Schema that validates user input. If a custom function is given, you should return a string or Error to show as a validation error, or undefined to accept the result.

validate
: (
value: string | undefined
value
) => {
if (!
value: string | undefined
value
|| !/^[a-z0-9_.-]+@[a-z0-9_.-]+\.[a-z]{2,}$/i.
RegExp.test(string: string): boolean

Returns a Boolean value that indicates whether or not a pattern exists in a searched string.

@paramstring String on which to perform the search.

test
(
value: string
value
)) return 'Please enter a valid email'
}
}),
username: (opts: {
results: {
email?: string;
password?: string;
};
}) => Promise<unknown> | undefined
username
: ({
results: {
email?: string;
password?: string;
}
results
}) =>
function text(opts: TextOptions): Promise<string | symbol>

The text prompt accepts a single line of text.

@seehttps://bomb.sh/docs/clack/packages/prompts/#text-input

@example

import { text } from '@clack/prompts';
const name = await text({
message: 'What is your name?',
placeholder: 'John Doe',
validate: (value) => {
if (!value || value.length < 2) return 'Name must be at least 2 characters';
return undefined;
},
});

text
({
TextOptions.message: string

The prompt message or question shown to the user above the input.

message
: 'What is your username?',
TextOptions.placeholder?: string

A visual hint shown when the field has no content.

placeholder
:
results: {
email?: string;
password?: string;
}
results
.
email?: string | undefined
email
?.
String.replace(searchValue: string | RegExp, replaceValue: string): string (+3 overloads)

Replaces text in a string, using a regular expression or search string.

@paramsearchValue A string or regular expression to search for.

@paramreplaceValue A string containing the text to replace. When the {@linkcode searchValue} is a RegExp, all matches are replaced if the g flag is set (or only those matches at the beginning, if the y flag is also present). Otherwise, only the first match of {@linkcode searchValue} is replaced.

replace
(/@.+$/, '').
String.toLowerCase(): string

Converts all the alphabetic characters in a string to lowercase.

toLowerCase
() ?? '',
TextOptions.validate?: Validate<string>

A function or a Standard Schema that validates user input. If a custom function is given, you should return a string or Error to show as a validation error, or undefined to accept the result.

validate
: (
value: string | undefined
value
) => {
// FOR DEMO PURPOSES ONLY! Use a robust validation library in production
if (!
value: string | undefined
value
||
value: string
value
.
String.length: number

Returns the length of a String object.

length
< 2) return 'Please enter at least 2 characters'
}
}),
password: (opts: {
results: {
email?: string;
username?: unknown;
};
}) => Promise<string | symbol | undefined> | undefined
password
: () =>
function password(opts: PasswordOptions): Promise<string | symbol>

The password prompt behaves like the

text

prompt, but the input is masked.

@seehttps://bomb.sh/docs/clack/packages/prompts/#password-input

@example

import { password } from '@clack/prompts';
const result = await password({
message: 'Enter your password',
});

password
({
PasswordOptions.message: string

The prompt message or question shown to the user above the input.

message
: 'Define your password'
}),
});

 What is your email address?
  user.name@example.com

 What is your username?
  bomb_sh

 Define your password
  ▪▪▪▪▪▪▪▪▪▪▪▪_

Options:

  • onCancel: Called when any one of the prompts is canceled.

The tasks function provides a convenient API for sequencing several asynchronous actions one after the other.

import {
const tasks: (tasks: Task[], opts?: CommonOptions) => Promise<void>

Define a group of tasks to be executed

tasks
} from "@clack/prompts";
await
function tasks(tasks: Task[], opts?: CommonOptions): Promise<void>

Define a group of tasks to be executed

tasks
([
{
title: string

Task title

title
: 'Downloading package',
task: (message: (string: string) => void) => string | Promise<string> | void | Promise<void>

Task function

task
: async () => {
// Do a fetch
return 'Download completed';
},
},
{
title: string

Task title

title
: "Un-archiving",
task: (message: (string: string) => void) => string | Promise<string> | void | Promise<void>

Task function

task
: async (
message: (string: string) => void
message
) => {
const
const parts: string[]
parts
:
interface Array<T>
Array
<string> = [/* ... */];
for (let
let index: number
index
= 0;
let index: number
index
<
const parts: string[]
parts
.
Array<T>.length: number

Gets or sets the length of the array. This is a number one higher than the highest index in the array.

length
;
let index: number
index
++) {
const
const type: string
type
=
const parts: string[]
parts
[
let index: number
index
];
// Update the message to indicate what is done
message: (string: string) => void
message
(`Un-archiving ${
const type: string
type
} (${
let index: number
index
+ 1}/${
const parts: string[]
parts
.
Array<T>.length: number

Gets or sets the length of the array. This is a number one higher than the highest index in the array.

length
})`);
// Do the un-archiving task
}
return 'Un-archiving completed';
},
},
{
title: string

Task title

title
: 'Linking',
task: (message: (string: string) => void) => string | Promise<string> | void | Promise<void>

Task function

task
: async () => {
// Do work
return 'Package linked';
},
},
]);

  Download completed

  Un-archiving lib (2/3)..

The intro function defines the beginning of an interaction. It accepts an optional string parameter which is displayed as a title for the interaction.

import {
const intro: (title?: string, opts?: CommonOptions) => void
intro
} from '@clack/prompts';
function intro(title?: string, opts?: CommonOptions): void
intro
('Welcome to clack');
  Welcome to clack

Options:

The outro function defines the end of an interaction. It accepts an optional string parameter which is displayed as a concluding message.

import {
const outro: (message?: string, opts?: CommonOptions) => void
outro
} from '@clack/prompts';
function outro(message?: string, opts?: CommonOptions): void
outro
('All operations are finished');

  All operations are finished
 

Options:

The cancel function defines an interruption of an interaction and therefore its end. It accepts an optional string parameter which is displayed as a cancellation message.

import {
const cancel: (message?: string, opts?: CommonOptions) => void
cancel
} from '@clack/prompts';
import
var process: NodeJS.Process
process
from 'node:process';
function cancel(message?: string, opts?: CommonOptions): void
cancel
('Installation canceled');
var process: NodeJS.Process
process
.
NodeJS.Process.exit(code?: number | string | null): never

The process.exit() method instructs Node.js to terminate the process synchronously with an exit status of code. If code is omitted, exit uses either the 'success' code 0 or the value of process.exitCode if it has been set. Node.js will not terminate until all the 'exit' event listeners are called.

To exit with a 'failure' code:

import { exit } from 'node:process';
exit(1);

The shell that executed Node.js should see the exit code as 1.

Calling process.exit() will force the process to exit as quickly as possible even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations to process.stdout and process.stderr.

In most situations, it is not actually necessary to call process.exit() explicitly. The Node.js process will exit on its own if there is no additional work pending in the event loop. The process.exitCode property can be set to tell the process which exit code to use when the process exits gracefully.

For instance, the following example illustrates a misuse of the process.exit() method that could lead to data printed to stdout being truncated and lost:

import { exit } from 'node:process';
// This is an example of what *not* to do:
if (someConditionNotMet()) {
printUsageToStdout();
exit(1);
}

The reason this is problematic is because writes to process.stdout in Node.js are sometimes asynchronous and may occur over multiple ticks of the Node.js event loop. Calling process.exit(), however, forces the process to exit before those additional writes to stdout can be performed.

Rather than calling process.exit() directly, the code should set the process.exitCode and allow the process to exit naturally by avoiding scheduling any additional work for the event loop:

import process from 'node:process';
// How to properly set the exit code while letting
// the process exit gracefully.
if (someConditionNotMet()) {
printUsageToStdout();
process.exitCode = 1;
}

If it is necessary to terminate the Node.js process due to an error condition, throwing an uncaught error and allowing the process to terminate accordingly is safer than calling process.exit().

In Worker threads, this function stops the current thread rather than the current process.

@sincev0.1.13

@paramcode The exit code. For string type, only integer strings (e.g.,'1') are allowed.

exit
(1);
  Installation canceled
 

Options:

The spinner function provides a loading indicator for long-running operations.

import {
const spinner: ({ indicator, onCancel, output, cancelMessage, errorMessage, frames, delay, signal, ...opts }?: SpinnerOptions) => SpinnerResult
spinner
} from '@clack/prompts';
const
const spin: SpinnerResult
spin
=
function spinner({ indicator, onCancel, output, cancelMessage, errorMessage, frames, delay, signal, ...opts }?: SpinnerOptions): SpinnerResult
spinner
();
const spin: SpinnerResult
spin
.
SpinnerResult.start(msg?: string): void
start
('Loading');
// Do something
const spin: SpinnerResult
spin
.
SpinnerResult.message(msg?: string): void
message
('Finishing');
// Do more things
const spin: SpinnerResult
spin
.
SpinnerResult.stop(msg?: string): void
stop
('Done');

  Loading...

The spinner provides multiple methods to indicate different completion states:

import {
const spinner: ({ indicator, onCancel, output, cancelMessage, errorMessage, frames, delay, signal, ...opts }?: SpinnerOptions) => SpinnerResult
spinner
} from '@clack/prompts';
const
const spin: SpinnerResult
spin
=
function spinner({ indicator, onCancel, output, cancelMessage, errorMessage, frames, delay, signal, ...opts }?: SpinnerOptions): SpinnerResult
spinner
();
const spin: SpinnerResult
spin
.
SpinnerResult.start(msg?: string): void
start
('Processing');
// Success - shows green checkmark
const spin: SpinnerResult
spin
.
SpinnerResult.stop(msg?: string): void
stop
('Completed successfully');
// Or cancel - shows red square
// spin.cancel('Operation cancelled');
// Or error - shows yellow triangle
// spin.error('An error occurred');
// Or clear - stops without showing any message
// spin.clear();

You can also check if the spinner was cancelled via SIGINT (Ctrl+C):

import {
const spinner: ({ indicator, onCancel, output, cancelMessage, errorMessage, frames, delay, signal, ...opts }?: SpinnerOptions) => SpinnerResult
spinner
} from '@clack/prompts';
const
const spin: SpinnerResult
spin
=
function spinner({ indicator, onCancel, output, cancelMessage, errorMessage, frames, delay, signal, ...opts }?: SpinnerOptions): SpinnerResult
spinner
({
SpinnerOptions.onCancel?: () => void
onCancel
: () => {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
('User pressed Ctrl+C');
}
});
const spin: SpinnerResult
spin
.
SpinnerResult.start(msg?: string): void
start
('Long running task');
// ... after some work
if (
const spin: SpinnerResult
spin
.
SpinnerResult.isCancelled: boolean
isCancelled
) {
// Handle cancellation
}
import {
const spinner: ({ indicator, onCancel, output, cancelMessage, errorMessage, frames, delay, signal, ...opts }?: SpinnerOptions) => SpinnerResult
spinner
,
function updateSettings(updates: ClackSettings): void
updateSettings
} from '@clack/prompts';
// Global customization for i18n
function updateSettings(updates: ClackSettings): void
updateSettings
({
ClackSettings.messages?: {
cancel?: string;
error?: string;
}

Custom messages for prompts

messages
: {
cancel?: string

Custom message to display when a spinner is cancelled

@default"Canceled"

cancel
: "Operation cancelled",
error?: string

Custom message to display when a spinner encounters an error

@default"Something went wrong"

error
: "An error occurred",
},
});
// Per-instance customization
const
const spin: SpinnerResult
spin
=
function spinner({ indicator, onCancel, output, cancelMessage, errorMessage, frames, delay, signal, ...opts }?: SpinnerOptions): SpinnerResult
spinner
({
SpinnerOptions.indicator?: "dots" | "timer"
indicator
: 'timer', // 'dots' (default) or 'timer' for elapsed time display
SpinnerOptions.cancelMessage?: string
cancelMessage
: "Process cancelled",
SpinnerOptions.errorMessage?: string
errorMessage
: "Process failed",
SpinnerOptions.frames?: string[]
frames
: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'], // Custom animation frames
SpinnerOptions.delay?: number
delay
: 80, // Animation delay in ms
SpinnerOptions.styleFrame?: (frame: string) => string
styleFrame
: (
frame: string
frame
) => `\x1b[35m${
frame: string
frame
}\x1b[0m`, // Custom frame styling
});
const spin: SpinnerResult
spin
.
SpinnerResult.start(msg?: string): void
start
('Loading');
// Do something
const spin: SpinnerResult
spin
.
SpinnerResult.stop(msg?: string): void
stop
('Done');

The indicator option supports two modes:

  • 'dots': Animated dots that cycle (default)
  • 'timer': Shows elapsed time like [5s] or [1m 30s]

The progress function displays a progress bar for long-running operations with multiple visual styles.

import {
function progress({ style, max: userMax, size: userSize, ...spinnerOptions }?: ProgressOptions): ProgressResult
progress
} from '@clack/prompts';
const
const prog: ProgressResult
prog
=
function progress({ style, max: userMax, size: userSize, ...spinnerOptions }?: ProgressOptions): ProgressResult
progress
({
ProgressOptions.style?: "light" | "heavy" | "block"
style
: 'heavy', // 'light', 'heavy', or 'block'
ProgressOptions.max?: number
max
: 100, // Maximum value (default: 100)
ProgressOptions.size?: number
size
: 40, // Width of the progress bar (default: 40)
});
const prog: ProgressResult
prog
.
SpinnerResult.start(msg?: string): void
start
('Processing files');
// Advance the progress bar
const prog: ProgressResult
prog
.
ProgressResult.advance(step?: number, msg?: string): void
advance
(10); // Advance by 10 steps
const prog: ProgressResult
prog
.
ProgressResult.advance(step?: number, msg?: string): void
advance
(25, 'Processing images...'); // Advance with a message update
// Update just the message
const prog: ProgressResult
prog
.
SpinnerResult.message(msg?: string): void
message
('Almost done...');
// Complete the progress
const prog: ProgressResult
prog
.
SpinnerResult.stop(msg?: string): void
stop
('All files processed');

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Processing images…

The progress bar supports three visual styles:

  • 'light': Uses thin lines ()
  • 'heavy': Uses thick lines () - default
  • 'block': Uses solid blocks ()

Additional methods:

  • advance(step?, msg?): Advance the progress bar by step (default: 1) and optionally update the message
  • message(msg): Update the displayed message without advancing
  • stop(msg?): Complete the progress bar with a success message
  • cancel(msg?): Stop with a cancellation indicator
  • error(msg?): Stop with an error indicator
  • clear(): Stop and clear the progress bar without a message

You can also use the timer indicator mode for time-based feedback:

import {
function progress({ style, max: userMax, size: userSize, ...spinnerOptions }?: ProgressOptions): ProgressResult
progress
} from '@clack/prompts';
const
const prog: ProgressResult
prog
=
function progress({ style, max: userMax, size: userSize, ...spinnerOptions }?: ProgressOptions): ProgressResult
progress
({
SpinnerOptions.indicator?: "dots" | "timer"
indicator
: 'timer', // Shows elapsed time instead of animated dots
ProgressOptions.style?: "light" | "heavy" | "block"
style
: 'block',
ProgressOptions.max?: number
max
: 50,
});
const prog: ProgressResult
prog
.
SpinnerResult.start(msg?: string): void
start
('Downloading');
// Progress shows: ████████████░░░░░░░░ Downloading [5s]

The note function renders a box around a message to draw a user’s attention. This is useful for displaying next steps and linking to your documentation towards the end of an interaction.

import {
const note: (message?: string, title?: string, opts?: NoteOptions) => void
note
} from '@clack/prompts';
function note(message?: string, title?: string, opts?: NoteOptions): void
note
(
'You can edit the file src/index.jsx',
'Next steps.'
);

  Next steps. ─────────────────────────╮
                                       
  You can edit the file src/index.jsx  
                                       
├───────────────────────────────────────╯

The second parameter (the title) is optional. You can also provide a format function to customize how each line is displayed:

import {
const note: (message?: string, title?: string, opts?: NoteOptions) => void
note
} from '@clack/prompts';
function note(message?: string, title?: string, opts?: NoteOptions): void
note
(
'Line 1\nLine 2\nLine 3',
'Formatted steps',
{
NoteOptions.format?: FormatFn
format
: (
line: string
line
: string) => `→ ${
line: string
line
}`
}
);

  Formatted steps
   ─────────────────────────────╮
                                
  → Line 1                      
  → Line 2                      
  → Line 3                      
                                
├────────────────────────────────╯

The box function renders a customizable box around text content. It’s similar to note but offers more styling options.

import {
const box: (message?: string, title?: string, opts?: BoxOptions) => void

Renders a customizable box around text content. It's similar to

note

but offers more styling options.

@seehttps://bomb.sh/docs/clack/packages/prompts/#box

@parammessage - The content to display inside the box.

@paramtitle - The title to display in the top border of the box.

@paramopts - Optional configuration for the box styling and behavior.

@example

import { box } from '@clack/prompts';
box('This is the content of the box', 'Box Title', {
contentAlign: 'center',
titleAlign: 'center',
width: 'auto',
rounded: true,
});

box
} from '@clack/prompts';
function box(message?: string, title?: string, opts?: BoxOptions): void

Renders a customizable box around text content. It's similar to

note

but offers more styling options.

@seehttps://bomb.sh/docs/clack/packages/prompts/#box

@parammessage - The content to display inside the box.

@paramtitle - The title to display in the top border of the box.

@paramopts - Optional configuration for the box styling and behavior.

@example

import { box } from '@clack/prompts';
box('This is the content of the box', 'Box Title', {
contentAlign: 'center',
titleAlign: 'center',
width: 'auto',
rounded: true,
});

box
('This is the content of the box', 'Box Title', {
BoxOptions.contentAlign?: BoxAlignment

Alignment of the content ('left', 'center', or 'right').

@default'left'

contentAlign
: 'center',
BoxOptions.titleAlign?: BoxAlignment

Alignment of the title ('left', 'center', or 'right').

@default'left'

titleAlign
: 'center',
BoxOptions.width?: number | "auto"

The width of the box, either 'auto' to fit the content or a number for a fixed width.

@default'auto'

width
: 'auto',
BoxOptions.rounded?: boolean

Use rounded corners when true, square corners when false.

@defaulttrue

rounded
: true,
});
  ╭──────────Box Title───────────╮
                                
    This is the content of the  
              box               
                                
  ╰──────────────────────────────╯

Options:

  • contentAlign: Alignment of the content ('left', 'center', or 'right'. default 'left').
  • titleAlign: Alignment of the title ('left', 'center', or 'right'. default 'left').
  • width: The width of the box, either 'auto' to fit the content or a number for a fixed width (default: 'auto').
  • titlePadding: Padding around the title (default: 1).
  • contentPadding: Padding around the content (default: 2).
  • rounded: Use rounded corners when true (default), square corners when false (default: true).
  • formatBorder: Custom function to style the border characters.

The taskLog prompt provides a way to display log output that is cleared on success. This is useful for showing progress or status updates that should be removed once the task is complete.

import {
const taskLog: (opts: TaskLogOptions) => {
message(msg: string, mopts?: TaskLogMessageOptions): void;
group(name: string): {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
};
error(message: string, opts?: TaskLogCompletionOptions): void;
success(message: string, opts?: TaskLogCompletionOptions): void;
}

Renders a log which clears on success and remains on failure

taskLog
} from '@clack/prompts';
const
const log: {
message(msg: string, mopts?: TaskLogMessageOptions): void;
group(name: string): {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
};
error(message: string, opts?: TaskLogCompletionOptions): void;
success(message: string, opts?: TaskLogCompletionOptions): void;
}
log
=
function taskLog(opts: TaskLogOptions): {
message(msg: string, mopts?: TaskLogMessageOptions): void;
group(name: string): {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
};
error(message: string, opts?: TaskLogCompletionOptions): void;
success(message: string, opts?: TaskLogCompletionOptions): void;
}

Renders a log which clears on success and remains on failure

taskLog
({
TaskLogOptions.title: string
title
: 'Installing dependencies',
TaskLogOptions.limit?: number
limit
: 10, // Limit visible log lines (optional)
TaskLogOptions.retainLog?: boolean
retainLog
: false, // Keep full log history (optional)
});
const log: {
message(msg: string, mopts?: TaskLogMessageOptions): void;
group(name: string): {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
};
error(message: string, opts?: TaskLogCompletionOptions): void;
success(message: string, opts?: TaskLogCompletionOptions): void;
}
log
.
function message(msg: string, mopts?: TaskLogMessageOptions): void
message
('Fetching package information...');
// Do some work
const log: {
message(msg: string, mopts?: TaskLogMessageOptions): void;
group(name: string): {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
};
error(message: string, opts?: TaskLogCompletionOptions): void;
success(message: string, opts?: TaskLogCompletionOptions): void;
}
log
.
function message(msg: string, mopts?: TaskLogMessageOptions): void
message
('Installing packages...');
// Do more work
const log: {
message(msg: string, mopts?: TaskLogMessageOptions): void;
group(name: string): {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
};
error(message: string, opts?: TaskLogCompletionOptions): void;
success(message: string, opts?: TaskLogCompletionOptions): void;
}
log
.
function success(message: string, opts?: TaskLogCompletionOptions): void
success
('Installation complete');

  Installing dependencies
  Fetching package information…
  Installing packages…
  Installation complete

Task logs support named groups, which allow you to organize logs into separate sections with their own headers and completion states:

import {
const taskLog: (opts: TaskLogOptions) => {
message(msg: string, mopts?: TaskLogMessageOptions): void;
group(name: string): {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
};
error(message: string, opts?: TaskLogCompletionOptions): void;
success(message: string, opts?: TaskLogCompletionOptions): void;
}

Renders a log which clears on success and remains on failure

taskLog
} from '@clack/prompts';
const
const log: {
message(msg: string, mopts?: TaskLogMessageOptions): void;
group(name: string): {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
};
error(message: string, opts?: TaskLogCompletionOptions): void;
success(message: string, opts?: TaskLogCompletionOptions): void;
}
log
=
function taskLog(opts: TaskLogOptions): {
message(msg: string, mopts?: TaskLogMessageOptions): void;
group(name: string): {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
};
error(message: string, opts?: TaskLogCompletionOptions): void;
success(message: string, opts?: TaskLogCompletionOptions): void;
}

Renders a log which clears on success and remains on failure

taskLog
({
TaskLogOptions.title: string
title
: 'Building project'
});
// Create a group for TypeScript compilation
const
const tsGroup: {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
}
tsGroup
=
const log: {
message(msg: string, mopts?: TaskLogMessageOptions): void;
group(name: string): {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
};
error(message: string, opts?: TaskLogCompletionOptions): void;
success(message: string, opts?: TaskLogCompletionOptions): void;
}
log
.
function group(name: string): {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
}
group
('Compiling TypeScript');
const tsGroup: {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
}
tsGroup
.
function message(msg: string, mopts?: TaskLogMessageOptions): void
message
('Processing src/index.ts...');
const tsGroup: {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
}
tsGroup
.
function message(msg: string, mopts?: TaskLogMessageOptions): void
message
('Processing src/utils.ts...');
const tsGroup: {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
}
tsGroup
.
function success(message: string): void
success
('TypeScript compiled');
// Create another group for bundling
const
const bundleGroup: {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
}
bundleGroup
=
const log: {
message(msg: string, mopts?: TaskLogMessageOptions): void;
group(name: string): {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
};
error(message: string, opts?: TaskLogCompletionOptions): void;
success(message: string, opts?: TaskLogCompletionOptions): void;
}
log
.
function group(name: string): {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
}
group
('Bundling');
const bundleGroup: {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
}
bundleGroup
.
function message(msg: string, mopts?: TaskLogMessageOptions): void
message
('Creating bundle...');
const bundleGroup: {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
}
bundleGroup
.
function message(msg: string, mopts?: TaskLogMessageOptions): void
message
('Minifying...');
const bundleGroup: {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
}
bundleGroup
.
function success(message: string): void
success
('Bundle created');
// Complete the overall task
const log: {
message(msg: string, mopts?: TaskLogMessageOptions): void;
group(name: string): {
message(msg: string, mopts?: TaskLogMessageOptions): void;
error(message: string): void;
success(message: string): void;
};
error(message: string, opts?: TaskLogCompletionOptions): void;
success(message: string, opts?: TaskLogCompletionOptions): void;
}
log
.
function success(message: string, opts?: TaskLogCompletionOptions): void
success
('Build complete');

Each group has its own message(), success(), and error() methods, allowing independent tracking of subtasks within a larger operation.

The log utilities allow you to add semantic contextual information during an interaction. Each function renders with specific styling to communicate status.

log is an object containing the following methods:

  • log.message displays a message without any symbols to communicate state
  • log.info displays a message with a neutral state
  • log.warn (alias log.warning) displays a message with a caution state
  • log.error displays a message with a danger state
  • log.success displays a message with a success state
  • log.step displays a message with a neutral, completed state
import {
const log: {
message: (message?: string | string[], { symbol, secondarySymbol, output, spacing, withGuide, }?: LogMessageOptions) => void;
info: (message: string, opts?: LogMessageOptions) => void;
... 4 more ...;
error: (message: string, opts?: LogMessageOptions) => void;
}
log
} from '@clack/prompts';
const log: {
message: (message?: string | string[], { symbol, secondarySymbol, output, spacing, withGuide, }?: LogMessageOptions) => void;
info: (message: string, opts?: LogMessageOptions) => void;
... 4 more ...;
error: (message: string, opts?: LogMessageOptions) => void;
}
log
.
message: (message?: string | string[], { symbol, secondarySymbol, output, spacing, withGuide, }?: LogMessageOptions) => void
message
('Entering directory "src"');
const log: {
message: (message?: string | string[], { symbol, secondarySymbol, output, spacing, withGuide, }?: LogMessageOptions) => void;
info: (message: string, opts?: LogMessageOptions) => void;
... 4 more ...;
error: (message: string, opts?: LogMessageOptions) => void;
}
log
.
info: (message: string, opts?: LogMessageOptions) => void
info
('No files to update');
const log: {
message: (message?: string | string[], { symbol, secondarySymbol, output, spacing, withGuide, }?: LogMessageOptions) => void;
info: (message: string, opts?: LogMessageOptions) => void;
... 4 more ...;
error: (message: string, opts?: LogMessageOptions) => void;
}
log
.
warn: (message: string, opts?: LogMessageOptions) => void
warn
('Directory is empty, skipping');
const log: {
message: (message?: string | string[], { symbol, secondarySymbol, output, spacing, withGuide, }?: LogMessageOptions) => void;
info: (message: string, opts?: LogMessageOptions) => void;
... 4 more ...;
error: (message: string, opts?: LogMessageOptions) => void;
}
log
.
warning: (message: string, opts?: LogMessageOptions) => void

alias for log.warn().

warning
('Directory is empty, skipping');
const log: {
message: (message?: string | string[], { symbol, secondarySymbol, output, spacing, withGuide, }?: LogMessageOptions) => void;
info: (message: string, opts?: LogMessageOptions) => void;
... 4 more ...;
error: (message: string, opts?: LogMessageOptions) => void;
}
log
.
error: (message: string, opts?: LogMessageOptions) => void
error
('Permission denied on file src/secret.js');
const log: {
message: (message?: string | string[], { symbol, secondarySymbol, output, spacing, withGuide, }?: LogMessageOptions) => void;
info: (message: string, opts?: LogMessageOptions) => void;
... 4 more ...;
error: (message: string, opts?: LogMessageOptions) => void;
}
log
.
success: (message: string, opts?: LogMessageOptions) => void
success
('Installation complete');
const log: {
message: (message?: string | string[], { symbol, secondarySymbol, output, spacing, withGuide, }?: LogMessageOptions) => void;
info: (message: string, opts?: LogMessageOptions) => void;
... 4 more ...;
error: (message: string, opts?: LogMessageOptions) => void;
}
log
.
step: (message: string, opts?: LogMessageOptions) => void
step
('Check files');

  Entering directory “src”

  No files to update

  Directory is empty, skipping

  Directory is empty, skipping

  Permission denied on file src/secret.js

  Installation complete

  Check files

The prompts package supports internationalization through the updateSettings function. You can customize the messages used by various prompts to match your preferred language.

import {
function updateSettings(updates: ClackSettings): void
updateSettings
,
const select: <Value>(opts: SelectOptions<Value>) => Promise<Value | symbol>
select
,
const cancel: (message?: string, opts?: CommonOptions) => void
cancel
} from '@clack/prompts';
// Update global messages
function updateSettings(updates: ClackSettings): void
updateSettings
({
ClackSettings.messages?: {
cancel?: string;
error?: string;
}

Custom messages for prompts

messages
: {
cancel?: string

Custom message to display when a spinner is cancelled

@default"Canceled"

cancel
: "Operación cancelada",
error?: string

Custom message to display when a spinner encounters an error

@default"Something went wrong"

error
: "Se ha producido un error",
},
ClackSettings.date?: {
monthNames?: string[];
messages?: {
required?: string;
invalidMonth?: string;
invalidDay?: (days: number, month: string) => string;
afterMin?: (min: Date) => string;
beforeMax?: (max: Date) => string;
};
}

Date prompt localization

date
: {
monthNames?: string[]

Month names for validation messages (January, February, ...)

monthNames
: [
"enero", "febrero", "marzo", "abril", "mayo", "junio",
"julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre",
],
messages?: {
required?: string;
invalidMonth?: string;
invalidDay?: (days: number, month: string) => string;
afterMin?: (min: Date) => string;
beforeMax?: (max: Date) => string;
}
messages
: {
required?: string

Shown when date is missing

required
: "Introduce una fecha válida",
invalidMonth?: string

Shown when month > 12

invalidMonth
: "Solo hay 12 meses",
invalidDay?: (days: number, month: string) => string

(days, monthName) => message for invalid day

invalidDay
: (
days: number
days
,
month: string
month
) => `Solo hay ${
days: number
days
} días en ${
month: string
month
}`,
afterMin?: (min: Date) => string

(min) => message when date is before minDate

afterMin
: (
min: Date
min
) => `La fecha debe ser el ${
min: Date
min
.
Date.toISOString(): string

Returns a date as a string value in ISO format.

toISOString
().
String.slice(start?: number, end?: number): string

Returns a section of a string.

@paramstart The index to the beginning of the specified portion of stringObj.

@paramend The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. If this value is not specified, the substring continues to the end of stringObj.

slice
(0, 10)} o posterior`,
beforeMax?: (max: Date) => string

(max) => message when date is after maxDate

beforeMax
: (
max: Date
max
) => `La fecha debe ser el ${
max: Date
max
.
Date.toISOString(): string

Returns a date as a string value in ISO format.

toISOString
().
String.slice(start?: number, end?: number): string

Returns a section of a string.

@paramstart The index to the beginning of the specified portion of stringObj.

@paramend The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. If this value is not specified, the substring continues to the end of stringObj.

slice
(0, 10)} o anterior`,
},
},
});
// Use the select prompt with translated content
const
const framework: symbol | "next" | "astro" | "svelte"
framework
= await
select<"next" | "astro" | "svelte">(opts: SelectOptions<"next" | "astro" | "svelte">): Promise<symbol | "next" | "astro" | "svelte">
select
({
SelectOptions<Value>.message: string
message
: 'Selecciona un framework',
SelectOptions<"next" | "astro" | "svelte">.options: ({
value: "next";
label?: string;
hint?: string;
disabled?: boolean;
} | {
value: "astro";
label?: string;
hint?: string;
disabled?: boolean;
} | {
value: "svelte";
label?: string;
hint?: string;
disabled?: boolean;
})[]
options
: [
{
value: "next"

Internal data for this option.

value
: 'next',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'Next.js',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Framework de React' },
{
value: "astro"

Internal data for this option.

value
: 'astro',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'Astro',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Enfocado en contenido' },
{
value: "svelte"

Internal data for this option.

value
: 'svelte',
label?: string

The optional, user-facing text for this option.

By default, the value is converted to a string.

label
: 'SvelteKit',
hint?: string

An optional hint to display to the user when this option might be selected.

By default, no hint is displayed.

hint
: 'Framework de compilación' },
]
});
// If the user cancels, they'll see the translated message
if (!
const framework: symbol | "next" | "astro" | "svelte"
framework
) {
function cancel(message?: string, opts?: CommonOptions): void
cancel
();
}

  Selecciona un framework
   Next.js (Framework de React)
  ○ Astro (Enfocado en contenido)
  ○ SvelteKit (Framework de compilación)

  Operación cancelada
 

The stream utilities allow you, like the log utilities, to add semantic contextual information during an interaction, except that the message contains an unknown number of lines. Each function renders with specific styling to communicate status.

import {
const stream: {
message: (iterable: Iterable<string> | AsyncIterable<string>, { symbol }?: LogMessageOptions) => Promise<void>;
info: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
... 4 more ...;
error: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
}
stream
} from "@clack/prompts";
import * as
module "node:fs"
fs
from "node:fs";
await
const stream: {
message: (iterable: Iterable<string> | AsyncIterable<string>, { symbol }?: LogMessageOptions) => Promise<void>;
info: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
... 4 more ...;
error: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
}
stream
.
message: (iterable: Iterable<string> | AsyncIterable<string>, { symbol }?: LogMessageOptions) => Promise<void>
message
(
module "node:fs"
fs
.
function createReadStream(path: fs.PathLike, options?: BufferEncoding | ReadStreamOptions): fs.ReadStream

options can include start and end values to read a range of bytes from the file instead of the entire file. Both start and end are inclusive and start counting at 0, allowed values are in the [0, Number.MAX_SAFE_INTEGER] range. If fd is specified and start is omitted or undefined, fs.createReadStream() reads sequentially from the current file position. The encoding can be any one of those accepted by Buffer.

If fd is specified, ReadStream will ignore the path argument and will use the specified file descriptor. This means that no 'open' event will be emitted. fd should be blocking; non-blocking fds should be passed to net.Socket.

If fd points to a character device that only supports blocking reads (such as keyboard or sound card), read operations do not finish until data is available. This can prevent the process from exiting and the stream from closing naturally.

By default, the stream will emit a 'close' event after it has been destroyed. Set the emitClose option to false to change this behavior.

By providing the fs option, it is possible to override the corresponding fs implementations for open, read, and close. When providing the fs option, an override for read is required. If no fd is provided, an override for open is also required. If autoClose is true, an override for close is also required.

import { createReadStream } from 'node:fs';
// Create a stream from some character device.
const stream = createReadStream('/dev/input/event0');
setTimeout(() => {
stream.close(); // This may not close the stream.
// Artificially marking end-of-stream, as if the underlying resource had
// indicated end-of-file by itself, allows the stream to close.
// This does not cancel pending read operations, and if there is such an
// operation, the process may still not be able to exit successfully
// until it finishes.
stream.push(null);
stream.read(0);
}, 100);

If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak. If autoClose is set to true (default behavior), on 'error' or 'end' the file descriptor will be closed automatically.

mode sets the file mode (permission and sticky bits), but only if the file was created.

An example to read the last 10 bytes of a file which is 100 bytes long:

import { createReadStream } from 'node:fs';
createReadStream('sample.txt', { start: 90, end: 99 });

If options is a string, then it specifies the encoding.

@sincev0.1.31

createReadStream
('./banner.txt', {
StreamOptions.encoding?: BufferEncoding | undefined
encoding
: 'utf-8' }));
await
const stream: {
message: (iterable: Iterable<string> | AsyncIterable<string>, { symbol }?: LogMessageOptions) => Promise<void>;
info: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
... 4 more ...;
error: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
}
stream
.
info: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>
info
((async function*() {
yield 'Open file...';
// Open file
yield ' \x1b[32mOK\x1b[39m\n';
yield 'Parsing file...';
// Parse data
yield ' \x1b[32mOK\x1b[39m';
return;
})());
await
const stream: {
message: (iterable: Iterable<string> | AsyncIterable<string>, { symbol }?: LogMessageOptions) => Promise<void>;
info: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
... 4 more ...;
error: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
}
stream
.
step: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>
step
([
'Job1...',
' \x1b[32mdone\x1b[39m\n',
'Job2...',
' \x1b[32mdone\x1b[39m\n',
'Job3...',
' \x1b[32mdone\x1b[39m',
]);


  ⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⣶⣶⣿⣿⣿⣿⣿⣿⣶⣶⣤⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
  ⠀⠀⠀⠀⠀⣠⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
  ⠀⠀⠀⣠⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
  ⠀⠀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
  ⠀⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀
  ⢰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⣀⠀⠀⠀⠀⣿⣿⣿⡿⠀⠀⠀⠀⣀⠀
  ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⠀⠀⠀⠀⢠⣿⣿⣶⣤⣄⣻⣿⣿⣇⣠⣴⣶⣿⣿⡀
  ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⢾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡧
  ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀⠀⠀⠀⠀⠉⢉⣿⣿⣿⣿⣿⣯⡉⠉⠀⠀⠀
  ⠸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀⠀⠀⠀⠀⢀⣴⣿⣿⣿⠟⢻⣿⣿⣿⣦⠀⠀⠀
  ⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠀⠀⠀⠀⠀⠀⠐⠿⣿⣿⣿⠏⠀⠀⢻⣿⣿⣿⠷⠀⠀
  ⠀⠀⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠛⠏⠀⠀⠀⠀⠹⠋⠁⠀⠀⠀
  ⠀⠀⠀⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
  ⠀⠀⠀⠀⠀⠙⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
  ⠀⠀⠀⠀⠀⠀⠀⠀⠉⠛⠻⠿⢿⣿⣿⣿⣿⡿⠿⠟⠛⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀


  Open file... OK
  Parsing file... OK

  Job1... done
  Job2... done
  Job3... done

Trims an option list to what fits the terminal, while keeping the active option (cursor) visible using a Clack style sliding window. Returns the lines to render.

import {
const limitOptions: <TOption>({ cursor, options, style, output, maxItems, columnPadding, rowPadding, }: LimitOptionsParams<TOption>) => string[]
limitOptions
} from '@clack/prompts';
import {
function styleText(format: ForegroundColors | BackgroundColors | Modifiers | Array<ForegroundColors | BackgroundColors | Modifiers>, text: string, options?: StyleTextOptions): string

This function returns a formatted text considering the format passed for printing in a terminal. It is aware of the terminal's capabilities and acts according to the configuration set via NO_COLOR, NODE_DISABLE_COLORS and FORCE_COLOR environment variables.

import { styleText } from 'node:util';
import { stderr } from 'node:process';
const successMessage = styleText('green', 'Success!');
console.log(successMessage);
const errorMessage = styleText(
'red',
'Error! Error!',
// Validate if process.stderr has TTY
{ stream: stderr },
);
console.error(errorMessage);

util.inspect.colors also provides text formats such as italic, and underline and you can combine both:

console.log(
util.styleText(['underline', 'italic'], 'My italic underlined message'),
);

When passing an array of formats, the order of the format applied is left to right so the following style might overwrite the previous one.

console.log(
util.styleText(['red', 'green'], 'text'), // green
);

The special format value none applies no additional styling to the text.

The full list of formats can be found in modifiers.

@paramformat A text format or an Array of text formats defined in util.inspect.colors.

@paramtext The text to to be formatted.

@sincev20.12.0

styleText
} from 'node:util';
const
const options: string[]
options
= ['apple', 'banana', 'cherry', 'date'];
const
const lines: string[]
lines
=
limitOptions<string>({ cursor, options, style, output, maxItems, columnPadding, rowPadding, }: LimitOptionsParams<string>): string[]
limitOptions
({
LimitOptionsParams<string>.options: string[]
options
,
LimitOptionsParams<TOption>.cursor: number
cursor
: 2,
LimitOptionsParams<TOption>.maxItems?: number
maxItems
: 8,
LimitOptionsParams<string>.style: (option: string, active: boolean) => string
style
: (
opt: string
opt
,
active: boolean
active
) =>
active: boolean
active
?
function styleText(format: ForegroundColors | BackgroundColors | Modifiers | Array<ForegroundColors | BackgroundColors | Modifiers>, text: string, options?: StyleTextOptions): string

This function returns a formatted text considering the format passed for printing in a terminal. It is aware of the terminal's capabilities and acts according to the configuration set via NO_COLOR, NODE_DISABLE_COLORS and FORCE_COLOR environment variables.

import { styleText } from 'node:util';
import { stderr } from 'node:process';
const successMessage = styleText('green', 'Success!');
console.log(successMessage);
const errorMessage = styleText(
'red',
'Error! Error!',
// Validate if process.stderr has TTY
{ stream: stderr },
);
console.error(errorMessage);

util.inspect.colors also provides text formats such as italic, and underline and you can combine both:

console.log(
util.styleText(['underline', 'italic'], 'My italic underlined message'),
);

When passing an array of formats, the order of the format applied is left to right so the following style might overwrite the previous one.

console.log(
util.styleText(['red', 'green'], 'text'), // green
);

The special format value none applies no additional styling to the text.

The full list of formats can be found in modifiers.

@paramformat A text format or an Array of text formats defined in util.inspect.colors.

@paramtext The text to to be formatted.

@sincev20.12.0

styleText
('cyan',
opt: string
opt
) :
function styleText(format: ForegroundColors | BackgroundColors | Modifiers | Array<ForegroundColors | BackgroundColors | Modifiers>, text: string, options?: StyleTextOptions): string

This function returns a formatted text considering the format passed for printing in a terminal. It is aware of the terminal's capabilities and acts according to the configuration set via NO_COLOR, NODE_DISABLE_COLORS and FORCE_COLOR environment variables.

import { styleText } from 'node:util';
import { stderr } from 'node:process';
const successMessage = styleText('green', 'Success!');
console.log(successMessage);
const errorMessage = styleText(
'red',
'Error! Error!',
// Validate if process.stderr has TTY
{ stream: stderr },
);
console.error(errorMessage);

util.inspect.colors also provides text formats such as italic, and underline and you can combine both:

console.log(
util.styleText(['underline', 'italic'], 'My italic underlined message'),
);

When passing an array of formats, the order of the format applied is left to right so the following style might overwrite the previous one.

console.log(
util.styleText(['red', 'green'], 'text'), // green
);

The special format value none applies no additional styling to the text.

The full list of formats can be found in modifiers.

@paramformat A text format or an Array of text formats defined in util.inspect.colors.

@paramtext The text to to be formatted.

@sincev20.12.0

styleText
('dim',
opt: string
opt
),
});

Options:

  • options: The list of options to display.
  • cursor: The index of the currently active/selected option.
  • style: A function that styles the given option string. The active parameter indicates whether the option is currently selected.
  • maxItems: Maximum number of options to display at once (default: Infinity).
  • columnPadding: Number of columns to reserve for padding (default: 0).
  • rowPadding: Number of rows to reserve for padding (default: 0).
  • All Common Options