包详细信息

reloquent

artdecocode232MIT1.4.1

Ask user configurable questions via read-line.

readline, ask, questions, stdin

自述文件

reloquent

npm version Build status

Reloquent allows to ask users a question, a confirmation (y/n), or a series of questions via the read-line interface.

yarn add reloquent
npm i reloquent

Table Of Contents

API

There are 4 types of calls to the API:

  • ask a single question as a string;
  • ask a single question as an object;
  • ask multiple questions.
  • ask for a confirmation;

Their respective methods can be accessed via the import statement:

import ask, { askSingle, confirm } from 'reloquent'

Question Type

When asking a question which is not a string, the question object should have the following structure:

Property Type Description Example
text string Display text. Required. js const q = { text: 'What is your name', }
validation (async) function A function which needs to throw an error if validation does not pass. js const q = { text: 'What is your name', validate(v) { if (!v.length) { throw new Error('Name required.') } }, }
postProcess (async) function A function to transform the answer. js const q = { text: 'What is your name', postProcess(v) { return `${v.toLowerCase()}` }, }
defaultValue string Default answer (shown to users in [default] brackets). js const q = { text: 'What is your name', defaultValue: 'Visitor', }
getDefault (async) function A function to execute to obtain the default value. js const q = { text: 'What is your name', async getDefault() { await git('config', 'user.name') }, }
password boolean Hide the inputs behind when typing the answer. js const q = { text: 'Please enter the password', password: true, }

If both defaultValue and getDefault are provided, the result of the getDefault takes precedence:

const q = {
  defaultValue: 'I desire it much',
  getDefault() {
    return 'I desire it much so'
  },
}

getDefault will get precedence

When the password property is set to true, the answer will be hidden behind the * symbols.

import { askSingle  } from 'reloquent'

const Password = async () => {
  const res = await askSingle({
    text: 'Please enter the password',
    password: true,
  })
  return res
}
Please enter the password: ********
<summary>Question extends readline.ReadLineOptions: A question.</summary> | Name | Type | Description | Default | | ------------ | --------------------------------------------------------------- | ----------------------------------------------------------------------- | ------- | | text* | string | The text to show to the user. | - | | defaultValue | string | The default answer to the question. | - | | password | boolean | Hide the inputs behind * when typing the answer. | false | | getDefault | () => (string | !Promise<string>) | The function which will get the default value, possibly asynchronously. | - | | validation | (answer: string) => void | The validation function which should throw on error. | - | | postProcess | (answer: string) => (string | !Promise<string>) | The transformation function for the answer. | - |

async askSingle(
  question: (string|!Question),
  timeout=: number,
): string

Ask user a question via the CLI. Returns the answer to the question. If a timeout is passed, the promise will expire after the specified number of milliseconds if the answer was not given.

  • <kbd>question*</kbd> (string | !Question): The question to present to the user.
  • <kbd>timeout</kbd> number (optional): How long to wait before rejecting the promise. Waits forever by default.

Questions can be asked as a simple string.

import { askSingle } from 'reloquent'

(async () => {
  try {
    const answer = await askSingle('What brought you her', 10000)
    console.log(`You've answered: ${answer}`)
  } catch (err) {
    console.log()
    console.log(err)
    console.log('Nevermind...')
  }
})()
What brought you her: I guess Art is the cause.
You've answered: I guess Art is the cause.

Alternatively, Reloquent can ask a question which is passed as an object of the Question type, and return a string.

import { askSingle } from 'reloquent'

(async () => {
  const answer = await askSingle({
    text: 'Do you wish me to stay so long?',
    validation(a) {
      if (a.length < 5) {
        throw new Error('The answer is too short')
      }
    },
    defaultValue: 'I desire it much',
    postProcess(a) {
      return `${a}!`
    },
    async getDefault() {
      return 'I desire it much so'
    },
  })
  console.log(answer)
})()
Do you wish me to stay so long? [I desire it much]
I desire it much!

async askQuestions(
  questions: !Questions,
  timeout=: number,
): !Object<string, string>

Ask user a series of questions via CLI and transform them into answers. Returns an object with keys as questions' texts and values as answers.

  • <kbd>questions*</kbd> !Questions: A set of questions.
  • <kbd>timeout</kbd> number (optional): How long to wait before rejecting the promise. Waits forever by default.

!Object<string, (string | !Question)> Questions: A set of questions.

import ask from 'reloquent'

const Ask = async () => {
  const questions = {
    title: {
      text: 'Title',
      validation(a) {
        if (!a) throw new Error('Please enter the title.')
      },
    },
    description: {
      text: 'Description',
      postProcess: s => s.trim(),
      defaultValue: 'A test default value',
    },
    date: {
      text: 'Date',
      async getDefault() {
        await new Promise(r => setTimeout(r, 200))
        return new Date().toLocaleString()
      },
    },
  }
  const res = await ask(questions)
  return res
}

If when provided with the following answers (leaving Date as it is), the result will be returned as an object:

Title: hello
Description: [A test default value] world
Date: [2/22/2020, 21:37:04] 

Result: {
  "title": "hello",
  "description": "world",
  "date": "2/22/2020, 21:37:04"
}

async confirm(
  question: (string|!Question),
  options=: !ConfirmOptions,
): boolean

Ask a yes/no question. Returns true when answer was y and false otherwise.

  • <kbd>question*</kbd> (string | !Question): The question, such as "Add default options", or "Continue to delete?". The question mark can added automatically.
  • <kbd>options</kbd> !ConfirmOptions (optional): Options for the confirmation question.

ConfirmOptions: Options for the confirmation question.

Name Type Description Default
defaultYes boolean Whether the default value is yes. true
timeout number How long to wait before rejecting the promise. Waits forever by default. -
import { confirm } from 'reloquent'

const Confirm = async (question) => {
  const res = await confirm(question, {
    defaultYes: false,
  })
  return res
}
Do you wish to continue (y/n): [n] y

Result: true

Copyright

Art Deco © Art Deco™ 2020

更新日志

22 February 2020

1.4.1

  • [doc] Appveyor badge.

22 February 2020

1.4.0

  • [feature] Questions now extend readline.ReadLineOptions.
  • [CI] Add Appveyor.

1 August 2019

1.3.2

  • [package] Publish the types directory.

1 May 2019

1.3.1

  • [fix] Quote the promise property.

30 April 2019

1.3.0

  • [externs] Publish externs and write types with namespace in a separate file.
  • [deps] Update all dev-dependencies + promto, upgrade structure.

3 February 2019

1.2.4

10 October 2018

1.2.3

  • [fix] Don't resolve on close (accepts confirmation with ctrl-c)

8 October 2018

1.2.2

  • [fix] Fix displaying newline when writing password.

1.2.1

  • [doc] Doc fix.

1.2.0

  • [feature] Ask for passwords behind *.

1.1.0

  • [feature] Ask for confirmation.
  • [package] Build with alamode.

26 June 2018

1.0.6

  • [package] Update maintainer.

1.0.5

  • [dep] Remove cross-env.

1.0.4

  • [doc] Do prevent scroll on npm.

1.0.3

  • [doc] Indent example to prevent scroll on npm.

1.0.2

  • [fix] Don't display same defaultValue to getDefault value, grey out defaultValue if getDefault takes precedence.
  • [doc] Start using documentary, split into files, document the Question type in a table.

11 June 2018

1.0.1

  • [build] build with source maps
  • [doc] document return type

9 June 2018

1.0.0

  • [ecma] update to modules
  • [api] change the api to allow to ask single questions.
  • [doc] update doc
  • [package] move to Art Deco Code

31 May 2017

0.2.0

  • [feature] askQuestions: ask multiple questions.

23 May 2017

0.1.0

  • Create reloquent: reading from readline interface with a timeout
  • [repo]: test, src, example, .eslintrc