From 77b61186e320383ad40e6b9dae25c18f2a8654fa Mon Sep 17 00:00:00 2001 From: RasPhilCo Date: Thu, 31 May 2018 17:17:17 -0700 Subject: [PATCH] feat: add timeout to prompt (#34) --- src/prompt.ts | 5 ++++- test/prompt.test.ts | 8 ++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/prompt.ts b/src/prompt.ts index a24c949b..fbffe2f9 100644 --- a/src/prompt.ts +++ b/src/prompt.ts @@ -6,6 +6,7 @@ import deps from './deps' export interface IPromptOptions { prompt?: string type?: 'normal' | 'mask' | 'hide' + timeout?: number /** * Requires user input if true, otherwise allows empty input */ @@ -20,6 +21,7 @@ interface IPromptConfig { isTTY: boolean required: boolean default?: string + timeout?: number } export default { @@ -66,7 +68,7 @@ function _prompt(name: string, inputOptions: Partial = {}): Prom function normal(options: IPromptConfig, retries = 100): Promise { if (retries < 0) throw new Error('no input') - return new Promise(resolve => { + return new Promise((resolve, reject) => { process.stdin.setEncoding('utf8') process.stderr.write(options.prompt) process.stdin.resume() @@ -79,5 +81,6 @@ function normal(options: IPromptConfig, retries = 100): Promise { resolve(data || options.default) } }) + setTimeout(() => reject(), options.timeout || 10000) }) } diff --git a/test/prompt.test.ts b/test/prompt.test.ts index d6b439b1..7603540d 100644 --- a/test/prompt.test.ts +++ b/test/prompt.test.ts @@ -27,4 +27,12 @@ describe('prompt', () => { await cli.done() expect(answer).to.equal(undefined) }) + + fancy + .stdout() + .stderr() + .end('timeouts with no input', async () => { + const response = await cli.prompt('Require input?', {timeout: 100}) + expect(response).to.not.exist + }) })