【NodeJS(TypeScript)】读取标准输入

以下是我在创建CLI工具时经常使用的函数。
在NodeJS中,通过使用标准的readline模块,我们可以从标准输入中接收输入。

中文选项:原料来源

import * as readline from "readline";

export const readFromCli = async (message: string, accept?: (input: string) => boolean): Promise<string> => {
  while (true) {
    const ans = await readFromCli2(message);
    if (!accept || accept(ans)) return ans;
  }
};

const readFromCli2 = async (message: string): Promise<string> => {
  const readlineInterface = readline.createInterface({ input: process.stdin, output: process.stdout });
  return new Promise<string>((resolve) => {
    readlineInterface.question(message, (ans) => {
      resolve(ans);
      readlineInterface.close();
    });
  });
};

使用方法

const color = await readFromCli('好きな色を入力 >', (input) => ['red', 'blue', 'yellow'].includes(input));

在接受第一个参数作为输入之前,在控制台中指定要显示的字符串。第二个参数是可选的,如果指定了一个函数,将循环提示输入直到该函数返回true。
在上述用法中,问用户喜欢的颜色,并重复接受输入直到输入了红色、蓝色或黄色为止。

文字引言

非常感谢您阅读到这里。
最近,我开始每周发布内容,所以如果您方便的话,也希望您能查看其他的文章。
因为我喜欢TypeScript,所以我会发布相关的内容。

    • 直近4週間:

10/15週_[TypeScript小テクニック]プロパティ名にパターンがあるときの型定義 – Template Literal Types

10/08週_【TypeScript】Union TypeとConditional Typeの組み合わせに注意!Distributive Conditional Typeについて

10/01週_「Announcing TypeScript 4.9 Beta」を読む

09/24週_【TypeORM】ちゃんとinitializeしないと、「EntityMetadataNotFoundError」が出るよ

广告
将在 10 秒后关闭
bannerAds