Skip to content

Commit

Permalink
Produce error on prompt in non-tty environment. (#891)
Browse files Browse the repository at this point in the history
* Produce error on prompt in non-tty environment.

* Fix build on node 8.

* Fix line order.

* Use Promise.reject()
  • Loading branch information
jhorbulyk committed Feb 29, 2020
1 parent 6a883e6 commit 8270551
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
11 changes: 11 additions & 0 deletions README.md
Expand Up @@ -62,6 +62,13 @@ inquirer
])
.then(answers => {
// Use user feedback for... whatever!!
})
.catch(error => {
if(error.isTtyError) {
// Prompt couldn't be rendered in the current environment
} else {
// Something else when wrong
}
});
```

Expand Down Expand Up @@ -283,6 +290,10 @@ Launches an instance of the users preferred editor on a temporary file. Once the

<a name="layouts"></a>

### Use in Non-Interactive Environments
`prompt()` requires that it is run in an interactive environment. (I.e. [One where `process.stdin.isTTY` is `true`](https://nodejs.org/docs/latest-v12.x/api/process.html#process_a_note_on_process_i_o)). If `prompt()` is invoked outside of such an environment, then `prompt()` will return a rejected promise with an error. For convenience, the error will have a `isTtyError` property to programmatically indicate the cause.


## User Interfaces and layouts

Along with the prompts, Inquirer offers some basic text UI.
Expand Down
10 changes: 10 additions & 0 deletions packages/inquirer/lib/inquirer.js
Expand Up @@ -24,6 +24,16 @@ inquirer.ui = {
*/
inquirer.createPromptModule = function(opt) {
var promptModule = function(questions) {
// Check if prompt is being called in TTY environment
// If it isn't return a failed promise
if (!process.stdin.isTTY) {
const nonTtyError = new Error(
'Prompts can not be meaningfully rendered in non-TTY environments'
);
nonTtyError.isTtyError = true;
return Promise.reject(nonTtyError);
}

var ui = new inquirer.ui.Prompt(promptModule.prompts, opt);
var promise = ui.run(questions);

Expand Down
28 changes: 28 additions & 0 deletions packages/inquirer/test/specs/inquirer.js
Expand Up @@ -673,4 +673,32 @@ describe('inquirer.prompt', function() {
expect(answers.q1).to.equal(true);
});
});

it('Throw an exception when run in non-tty', function() {
var original = process.stdin.isTTY;
delete process.stdin.isTTY;

var prompt = inquirer.createPromptModule();

var prompts = [
{
type: 'confirm',
name: 'q1',
message: 'message'
}
];

var promise = prompt(prompts);

return promise
.then(() => {
// Failure
process.stdin.isTTY = original;
expect(true).to.equal(false);
})
.catch(error => {
process.stdin.isTTY = original;
expect(error.isTtyError).to.equal(true);
});
});
});

0 comments on commit 8270551

Please sign in to comment.