Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A collection of common interactive command line user interfaces.

License

NotificationsYou must be signed in to change notification settings

SBoudrias/Inquirer.js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Inquirer Logo

Inquirer

npmFOSSA Status

A collection of common interactive command line user interfaces.

List prompt

Give it a try in your own terminal!

npx @inquirer/demo@latest

Installation

npmyarnpnpmbun
npm install @inquirer/prompts
yarn add @inquirer/prompts
pnpm add @inquirer/prompts
bun add @inquirer/prompts

Note

Inquirer recently underwent a rewrite from the ground up to reduce the package size and improve performance. The previous version of the package is still maintained (though not actively developed), and offered hundreds of community contributed prompts that might not have been migrated to the latest API. If this is what you're looking for, theprevious package is over here.

Usage

import{input}from'@inquirer/prompts';constanswer=awaitinput({message:'Enter your name'});

Prompts

Input prompt

import{input}from'@inquirer/prompts';

See documentation for usage example and options documentation.

Select prompt

import{select}from'@inquirer/prompts';

See documentation for usage example and options documentation.

Checkbox prompt

import{checkbox}from'@inquirer/prompts';

See documentation for usage example and options documentation.

Confirm prompt

import{confirm}from'@inquirer/prompts';

See documentation for usage example and options documentation.

search prompt

import{search}from'@inquirer/prompts';

See documentation for usage example and options documentation.

Password prompt

import{password}from'@inquirer/prompts';

See documentation for usage example and options documentation.

Expand prompt closedExpand prompt expanded

import{expand}from'@inquirer/prompts';

See documentation for usage example and options documentation.

Launches an instance of the users preferred editor on a temporary file. Once the user exits their editor, the content of the temporary file is read as the answer. The editor used is determined by reading the $VISUAL or $EDITOR environment variables. If neither of those are present, the OS default is used (notepad on Windows, vim on Mac or Linux.)

import{editor}from'@inquirer/prompts';

See documentation for usage example and options documentation.

Very similar to theinput prompt, but with built-in number validation configuration option.

import{number}from'@inquirer/prompts';

See documentation for usage example and options documentation.

Raw list prompt

import{rawlist}from'@inquirer/prompts';

See documentation for usage example and options documentation.

Create your own prompts

TheAPI documentation is over here, and ourtesting utilities here.

Advanced usage

All inquirer prompts are a function taking 2 arguments. The first argument is the prompt configuration (unique to each prompt). The second is providing contextual or runtime configuration.

The context options are:

PropertyTypeRequiredDescription
inputNodeJS.ReadableStreamnoThe stdin stream (defaults toprocess.stdin)
outputNodeJS.WritableStreamnoThe stdout stream (defaults toprocess.stdout)
clearPromptOnDonebooleannoIf true, we'll clear the screen after the prompt is answered
signalAbortSignalnoAn AbortSignal to cancel prompts asynchronously

Warning

When providing an input stream or pipingprocess.stdin, it's very likely you need to callprocess.stdin.setRawMode(true)before calling inquirer functions. Node.js usually does it automatically, but when we shadow the stdin, Node can loss trackand not know it has to. If the prompt isn't interactive (arrows don't work, etc), it's likely due to this.

Example:

import{confirm}from'@inquirer/prompts';constallowEmail=awaitconfirm({message:'Do you allow us to send you email?'},{output:newStream.Writable({write(chunk,_encoding,next){// Do somethingnext();},}),clearPromptOnDone:true,},);

Canceling prompt

This can be done with either anAbortController orAbortSignal.

// Example 1: using built-in AbortSignal utilitiesimport{confirm}from'@inquirer/prompts';constanswer=awaitconfirm({ ...},{signal:AbortSignal.timeout(5000)});
// Example 2: implementing custom cancellation with an AbortControllerimport{confirm}from'@inquirer/prompts';constcontroller=newAbortController();setTimeout(()=>{controller.abort();// This will reject the promise},5000);constanswer=awaitconfirm({ ...},{signal:controller.signal});

Recipes

Handlingctrl+c gracefully

When a user pressctrl+c to exit a prompt, Inquirer rejects the prompt promise. This is the expected behavior in order to allow your program to teardown/cleanup its environment. When usingasync/await, rejected promises throw their error. When unhandled, those errors print their stack trace in your user's terminal.

ExitPromptError: User force closed the prompt with 0 null  at file://example/packages/core/dist/esm/lib/create-prompt.js:55:20  at Emitter.emit (file://example/node_modules/signal-exit/dist/mjs/index.js:67:19)  at #processEmit (file://example/node_modules/signal-exit/dist/mjs/index.js:236:27)  at #process.emit (file://example/node_modules/signal-exit/dist/mjs/index.js:187:37)  at process.callbackTrampoline (node:internal/async_hooks:130:17)

This isn't a great UX, which is why we highly recommend you to handle those errors gracefully.

First option is to wrap your scripts intry/catch; likewe do in our demo program. Or handle the error in your CLI framework mechanism; for exampleClipanion catch method.

Lastly, you could handle the error globally with an event listener and silence it.

process.on('uncaughtException',(error)=>{if(errorinstanceofError&&error.name==='ExitPromptError'){console.log('👋 until next time!');}else{// Rethrow unknown errorsthrowerror;}});

Get answers in an object

When asking many questions, you might not want to keep one variable per answer everywhere. In which case, you can put the answer inside an object.

import{input,confirm}from'@inquirer/prompts';constanswers={firstName:awaitinput({message:"What's your first name?"}),allowEmail:awaitconfirm({message:'Do you allow us to send you email?'}),};console.log(answers.firstName);

Ask a question conditionally

Maybe some questions depend on some other question's answer.

import{input,confirm}from'@inquirer/prompts';constallowEmail=awaitconfirm({message:'Do you allow us to send you email?'});letemail;if(allowEmail){email=awaitinput({message:'What is your email address'});}

Get default value after timeout

import{input}from'@inquirer/prompts';constanswer=awaitinput({message:'Enter a value (timing out in 5 seconds)'},{signal:AbortSignal.timeout(5000)},).catch((error)=>{if(error.name==='AbortPromptError'){return'Default value';}throwerror;});

Using as pre-commit/git hooks, or scripts

By default scripts ran from tools likehusky/lint-staged might not run inside an interactive shell. In non-interactive shell, Inquirer cannot run, and users cannot send keypress events to the process.

For it to work, you must make sure you start atty (or "interactive" input stream.)

If those scripts are set within yourpackage.json, you can define the stream like so:

"precommit":"my-script < /dev/tty"

Or if in a shell script file, you'll do it like so: (on Windows that's likely your only option)

#!/bin/shexec< /dev/ttynode my-script.js

Using with nodemon

When using inquirer prompts with nodemon, you need to pass the--no-stdin flag for everything to work as expected.

npx nodemon ./packages/demo/demos/password.mjs --no-stdin

Note that for most of you, you'll be able to use the new watch-mode built-in Node. This mode works out of the box with inquirer.

# One of depending on your neednode --watch script.jsnode --watch-path=packages/ packages/demo/

Wait for config

Maybe some question configuration require to await a value.

import{confirm}from'@inquirer/prompts';constanswer=awaitconfirm({message:awaitgetMessage()});

Usage withnpx within bash scripts

You can use Inquirer prompts directly in the shell vianpx, which is useful for quick scripts orpackage.json commands.

A community library,@inquirer-cli, exposes each prompt as a standalone CLI.

For example, to prompt for input:

name=$(npx -y @inquirer-cli/input -r"What is your name?")echo"Hello,$name!"

Or to create an interactive version bump:

$ npm version$(npx -y @inquirer-cli/select -c patch -c minor -c major'Select Version')

Find out more:@inquirer-cli.

Community prompts

If you created a cool prompt,send us a PR adding it to the list below!

Interactive List Prompt
Select a choice either with arrow keys + Enter or by pressing a key associated with a choice.

? Choose an option:>   Run command (D)    Quit (Q)

Action Select Prompt
Choose an item from a list and choose an action to take by pressing a key.

? Choose a file Open <O> Edit <E> Delete <X>❯ image.png  audio.mp3  code.py

Table Multiple Prompt
Select multiple answer from a table display.

Choose between choices? (Press<space> to select,<Up and Down> to move rows,<Left and Right> to move columns)┌──────────┬───────┬───────┐│ 1-2 of 2 │ Yes?  │ No?|├──────────┼───────┼───────┤│ Choice 1 │ [ ◯ ] │   ◯|├──────────┼───────┼───────┤│ Choice 2 │   ◯   │   ◯|└──────────┴───────┴───────┘

Toggle Prompt
Confirm with a toggle. Select a choice with arrow keys + Enter.

? Do you want to continue? no / yes

Sortable Checkbox Prompt
The same as built-in checkbox prompt, but also allowing to reorder choices using ctrl+up/down.

? Which PRs and in what order would you like to merge? (Press <space> to select, <a> to toggle all, <i> to invert selection, <ctrl+up> to move item up, <ctrl+down> to move item down, and <enter> to proceed)❯ ◯ PR 1  ◯ PR 2  ◯ PR 3

Multi Select Prompt

An inquirer select that supports multiple selections and filtering/searching.

? Choose your OS, IDE, PL, etc. (Press <tab> to select/deselect, <backspace> to remove selectedoption, <enter> to select option)>>  vue>[ ] vue [ ] vuejs [ ] fuelphp [ ] venv [ ] vercel (Use arrow keys to reveal more options)

File Selector Prompt
A file selector, you can navigate freely between directories, choose what type of files you want to allow and it is fully customizable.

? Select a file:/main/path/├── folder1/├── folder2/├── folder3/├── file1.txt├── file2.pdf└── file3.jpg (not allowed)━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━Use ↑↓ to navigate through the listPress<esc> to navigate to the parent directoryPress<enter> toselecta file or navigate to a directory

Select Prompt with Stateful Banner
The same as built-in select prompt, but it also displays a banner above the prompt which can be updated with asetState function. For example, it can display the results of a long-running command without making the user wait to see the prompt.

Initial display:

Directory size: loading...? Choose an option❯ Rename  Copy  Delete

A moment later:

Directory size: 123M? Choose an option❯ Rename  Copy  Delete

Ordered Checkbox Prompt
A sortable checkbox prompt that maintains the order of selection. Perfect for prioritizing tasks or ranking options.

? Configure your development workflow:  [1] Set up CI/CD pipeline❯ [3] Code quality tools  [ ] Documentation  [2] Performance monitoring ──────────────- Legacy system (disabled)(Linting, formatting, and analysis)

Checkbox Plus Plus Prompt
A modern multiselect checkbox prompt with search and filter capabilities, highlighting, autocomplete, and improved UX. Supports both ESM and CommonJS and is compatible with @inquirer/core v10+.

? Select colors [searching: "re"]❯ ◉ The red color  ◯ The green color  ◉ The purple color  ◯ The orange color↑↓ navigate • space de/select • type search • 2 selected  • ⏎ submit

License

Copyright (c) 2023 Simon Boudrias (twitter:@vaxilart)
Licensed under the MIT license.

About

A collection of common interactive command line user interfaces.

Topics

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Packages

No packages published

Contributors224


[8]ページ先頭

©2009-2025 Movatter.jp