1
0

More than 1 year has passed since last update.

【NodeJS(TypeScript)】標準入力から読み取る

Posted at

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));

第1引数で入力を受け付ける前にコンソールに出す文字列を指定します。第2引数は省略可能で、関数を指定するとその関数がtrueを返却するまで入力を再度促します。
上記の使い方では、好きな色を聞いて、red,blue,yellowのいずれかが入力されるまで繰り返し入力を受け付けます。

記事紹介

ここまで読んでいただき、ありがとうございます。
最近、毎週投稿を初めて何とか続いているので、もしよければ他の記事も見て頂けると嬉しいです。
TypeScriptが好きなので、それ関連の投稿をしてます。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0