at backyard

Color my life with the chaos of trouble.

Node.jsの標準入力で1文字ずつの入力に対して処理を発行したいとき

Node.jsの標準入力で1文字ずつの入力に対して処理を発行したいケースがある場合のメモ。

stdin.setRawMode(true) にすることでキー入力に対してイベントを発行できるようになる。
(これをつけない場合、Enterキーが押された場合のみ on('data', () => ... が動くようになる)

実際にキー入力に対して処理を動かす際のサンプル。

なお、Ctrl + C と、Enterキー を押した場合のみプロセス終了などの処理を動かすようにしている。

// これをつけないとEnterキーが押されたときだけストリームを取得することになる
process.stdin.setRawMode(true);

process.stdin.resume();
process.stdin.setEncoding('utf8');

let output = '';

process.stdin.on('data', (key => {
  // ctrl-cを押した場合、プロセスを終了する
  if(key === '\x03') {
    console.log('Exit process');
    process.exit();
  }

  // Enterキーを押した際に動く(プロセス終了)
  if(key === '\r') {
    console.log('Output: ', output);
    process.exit(0)
  }

  // 入力されたキーを結合して標準出力させる
  output = output + key;
  process.stdout.write(output + '\n');
}));

なお、このようにstdin.setRawMode(true)にした場合、下記のような処理は検知しなくなるようだった。

stdin.on('end', () => {
  ・
  ・
  ・
});

process.on('SIGINT', () => {
  ・
  ・
  ・
});