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.
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.
if (!value || value.length<2) return'Name must be at least 2 characters';
returnundefined;
},
});
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.
if (!value || value.length<2) return'Name must be at least 2 characters';
returnundefined;
},
});
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..
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.
@default ― false
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.
@param ― string 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.
@param ― string 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.
@param ― string 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.
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
@default ― false
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.
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.
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 additionalwork 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.
@since ― v0.1.13
@param ― code The exit code. For string type, only integer strings (e.g.,'1') are allowed.
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.
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.
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.
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.
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.
Returns the elements of an array that meet the condition specified in a callback function.
@param ― predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
@param ― thisArg 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
constt: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.
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.
@param ― searchString search string
@param ― position If position is undefined, 0 is assumed, so as to search all of the String.
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
constla: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
constlb: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.
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.
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(
constq:string
q) ?0:1;
return
constsa:0|1
sa-
constsb:0|1
sb||
constla: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.
@param ― that String to compare to target string
@param ― locales 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.
@param ― options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
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.
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.
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.
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..
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.
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.
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.
if (!value || value.length<2) return'Name must be at least 2 characters';
returnundefined;
},
});
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.
Replaces text in a string, using a regular expression or search string.
@param ― searchValue A string or regular expression to search for.
@param ― replaceValue 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
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.
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 additionalwork 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.
@since ― v0.1.13
@param ― code The exit code. For string type, only integer strings (e.g.,'1') are allowed.
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
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.
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.
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
The prompts package supports internationalization through the updateSettings function. You can customize the messages used by various prompts to match your preferred language.
@param ― start The index to the beginning of the specified portion of stringObj.
@param ― end 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.
@param ― start The index to the beginning of the specified portion of stringObj.
@param ― end 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.
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 {
conststream: {
message: (iterable:Iterable<string> |AsyncIterable<string>, { symbol }?:LogMessageOptions) =>Promise<void>;
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.
// 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:
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.
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.
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.
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.