7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Node.js: CLIでユーザの入力をインタラクティブに読み取る3行ぽっきりの実装

Posted at

Node.jsでCLIアプリケーションを作る際に、インタラクティブなプロンプトを出して、ユーザのテキスト入力を受け取る実装を紹介する。

この実装は3行で済み、外部ライブラリを必要としない。

デモ

こんな感じで、ターミナルにタイプした文字をNode.jsで受け取るものを実装する。

2019-11-21 16-35-56.2019-11-21 16_36_49.gif

実装

上でのデモの完全な実装は次のコードになる:

function readText() {
	process.stdin.resume()
	return new Promise(r => process.stdin.once('data', r))
		.finally(() => process.stdin.pause())
}

(async function main () {
	process.stdout.write('> ')
	process.stdout.write('< ' + await readText())
	process.stdout.write('> ')
	process.stdout.write('< ' + await readText())
})()

このうち、ユーザ入力を受け取るコアの部分は次の3行:

process.stdin.resume()
new Promise(r => process.stdin.once('data', r))
	.finally(() => process.stdin.pause())
  • 1行目のresumeで標準入力の受付を再開する。
    • どこかの処理ですでにpauseしていた場合に再開しないと2行目が動かないため。
  • 2行目で標準入力を1回だけ受け取る。
  • 3行目のpauseで標準入力の受け付けを停止する。
    • ずっと受け付けっぱなしなると、CLIのプロセスが終了しないため。
7
2
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
7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?