Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
@inquirer/prompts
Advanced tools
@inquirer/prompts is a collection of prompt modules for the Inquirer.js library, which is used to create interactive command-line interfaces. It provides a variety of prompt types to gather user input in a structured and user-friendly manner.
Text Prompt
The text prompt allows you to ask the user for a simple text input. In this example, the user is asked for their name, and the input is then printed to the console.
const { text } = require('@inquirer/prompts');
(async () => {
const answer = await text({ message: 'What is your name?' });
console.log(`Hello, ${answer}!`);
})();
Password Prompt
The password prompt is used to securely gather password input from the user. The input is masked to ensure privacy.
const { password } = require('@inquirer/prompts');
(async () => {
const answer = await password({ message: 'Enter your password:' });
console.log('Password received');
})();
Confirm Prompt
The confirm prompt asks the user a yes/no question. The response is a boolean value indicating the user's choice.
const { confirm } = require('@inquirer/prompts');
(async () => {
const answer = await confirm({ message: 'Do you want to continue?' });
console.log(`User response: ${answer}`);
})();
List Prompt
The list prompt presents a list of options to the user, allowing them to select one. The selected option is then returned.
const { list } = require('@inquirer/prompts');
(async () => {
const answer = await list({ message: 'Choose a color:', choices: ['Red', 'Green', 'Blue'] });
console.log(`You chose: ${answer}`);
})();
Checkbox Prompt
The checkbox prompt allows the user to select multiple options from a list. The selected options are returned as an array.
const { checkbox } = require('@inquirer/prompts');
(async () => {
const answer = await checkbox({ message: 'Select toppings:', choices: ['Pepperoni', 'Cheese', 'Mushrooms'] });
console.log(`You selected: ${answer.join(', ')}`);
})();
The 'prompts' package is another library for creating interactive command-line prompts. It offers a similar range of prompt types and is known for its simplicity and ease of use. Compared to @inquirer/prompts, 'prompts' is often praised for its minimalistic design and straightforward API.
The 'enquirer' package provides a rich set of prompt types and is designed to be highly customizable. It offers more advanced features and customization options compared to @inquirer/prompts, making it suitable for more complex CLI applications.
The 'vorpal' package is a framework for building interactive CLI applications. It includes built-in support for prompts and offers additional features like command history and tab completion. While it provides similar prompt functionalities, it is more comprehensive and suited for building full-fledged CLI tools.
A collection of common interactive command line user interfaces.
Give it a try in your own terminal!
npx @inquirer/demo@latest
npm | yarn |
---|---|
|
|
[!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, the previous package is over here.
import { input } from '@inquirer/prompts';
const answer = await input({ message: 'Enter your name' });
import { input } from '@inquirer/prompts';
See documentation for usage example and options documentation.
import { select } from '@inquirer/prompts';
See documentation for usage example and options documentation.
import { checkbox } from '@inquirer/prompts';
See documentation for usage example and options documentation.
import { confirm } from '@inquirer/prompts';
See documentation for usage example and options documentation.
import { search } from '@inquirer/prompts';
See documentation for usage example and options documentation.
import { password } from '@inquirer/prompts';
See documentation for usage example and options documentation.
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 the input
prompt, but with built-in number validation configuration option.
import { number } from '@inquirer/prompts';
See documentation for usage example and options documentation.
import { rawlist } from '@inquirer/prompts';
See documentation for usage example and options documentation.
The API documentation is over here, and our testing utilities here.
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:
Property | Type | Required | Description |
---|---|---|---|
input | NodeJS.ReadableStream | no | The stdin stream (defaults to process.stdin ) |
output | NodeJS.WritableStream | no | The stdout stream (defaults to process.stdout ) |
clearPromptOnDone | boolean | no | If true, we'll clear the screen after the prompt is answered |
signal | AbortSignal | no | An AbortSignal to cancel prompts asynchronously |
Example:
import { confirm } from '@inquirer/prompts';
const allowEmail = await confirm(
{ message: 'Do you allow us to send you email?' },
{
output: new Stream.Writable({
write(chunk, _encoding, next) {
// Do something
next();
},
}),
clearPromptOnDone: true,
},
);
This can preferably be done with either an AbortController
or AbortSignal
.
// Example 1: using built-in AbortSignal utilities
import { confirm } from '@inquirer/prompts';
const answer = await confirm({ ... }, { signal: AbortSignal.timeout(5000) });
// Example 1: implementing custom cancellation logic
import { confirm } from '@inquirer/prompts';
const controller = new AbortController();
setTimeout(() => {
controller.abort(); // This will reject the promise
}, 5000);
const answer = await confirm({ ... }, { signal: controller.signal });
Alternatively, all prompt functions are returning a cancelable promise. This special promise type has a cancel
method that'll cancel and cleanup the prompt.
On calling cancel
, the answer promise will become rejected.
import { confirm } from '@inquirer/prompts';
const promise = confirm(...); // Warning: for this pattern to work, `await` cannot be used.
promise.cancel();
ctrl+c
gracefullyWhen a user press ctrl+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 using async/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 in try/catch
; like we do in our demo program. Or handle the error in your CLI framework mechanism; for example Clipanion catch
method.
Lastly, you could handle the error globally with an event listener and silence it.
process.on('uncaughtException', (error) => {
if (error instanceof Error && error.name === 'ExitPromptError') {
console.log('š until next time!');
} else {
// Rethrow unknown errors
throw error;
}
});
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';
const answers = {
firstName: await input({ message: "What's your first name?" }),
allowEmail: await confirm({ message: 'Do you allow us to send you email?' }),
};
console.log(answers.firstName);
Maybe some questions depend on some other question's answer.
import { input, confirm } from '@inquirer/prompts';
const allowEmail = await confirm({ message: 'Do you allow us to send you email?' });
let email;
if (allowEmail) {
email = await input({ message: 'What is your email address' });
}
import { input } from '@inquirer/prompts';
const answer = await input(
{ message: 'Enter a value (timing out in 5 seconds)' },
{ signal: AbortSignal.timeout(5000) },
).catch((error) => {
if (error.name === 'AbortPromptError') {
return 'Default value';
}
throw error;
});
By default scripts ran from tools like husky
/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 a tty
(or "interactive" input stream.)
If those scripts are set within your package.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/sh
exec < /dev/tty
node my-script.js
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 need
node --watch script.js
node --watch-path=packages/ packages/demo/
Maybe some question configuration require to await a value.
import { confirm } from '@inquirer/prompts';
const answer = await confirm({ message: await getMessage() });
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
An inquirer select that supports multiple selections and filtering/searching.
? Choose your OS, IDE, PL, etc. (Press <tab> to select/deselect, <backspace> to remove selected
option, <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 list
Press <esc> to navigate to the parent directory
Press <enter> to select a file or navigate to a directory
Copyright (c) 2023 Simon Boudrias (twitter: @vaxilart)
Licensed under the MIT license.
FAQs
Inquirer prompts, combined in a single package
The npm package @inquirer/prompts receives a total of 1,961,508 weekly downloads. As such, @inquirer/prompts popularity was classified as popular.
We found that @inquirer/prompts demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.Ā It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.