3
3

More than 5 years have passed since last update.

[Node.js] Control-C をハンドリングするのに便利なツール

Last updated at Posted at 2014-11-05

Control-C をハンドリングするのに便利なツール

npm に control-c というパッケージを登録した。

例えば、以下の様な事ができる。

  • 1回の Control-C のキーインで、プログラムの状態を表示する。
  • 連続2回の Control-C のキーイン(ダブルControl-C)で、リセットとか再初期化を行う。
  • 連続3回以上の Control-C のキーイン(トリプルControl-C)で、クリーンアップして正常に終了させる。

control-c.jpg

インストール:

$ npm install control-c

使い方:

var ControlC = require('control-c');

例:

example.js
'use strict';

var ControlC = require('control-c');

var singleCount = 0;
var doubleCount = 0;

ControlC(
  function singleControlC() { console.log('Single:', ++singleCount); },
  function doubleControlC() { console.log('Double:', ++doubleCount); },
  function tripleControlC() { console.log('Reset'); singleCount = doubleCount = 0; },
  function quadrupleControlC() { console.log('Exit'); process.nextTick(process.exit); });

console.log('press control-c in 30 seconds.');
setTimeout(function () {}, 30000);

試し方:

$ node example

1回のControl-Cというのは、普通にできると思う。シングルControl-Cだ。

連続2回以上のControl-Cというのは、500ミリ秒以内に続けて次のControl-Cを入力してください。
ダブルクリックならぬダブルControl-Cとか、トリプルControl-Cの様な感じ。

あとがき

もちろん4回とか5回以上のControl-Cハンドラーも定義できるけど、指がつりそうになったり、何回押したか数えられなくなるかもしれないよ。

おしまい

3
3
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
3
3