baseUI.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. 'use strict';
  2. var _ = require('lodash');
  3. var readlineFacade = require('readline2');
  4. /**
  5. * Base interface class other can inherits from
  6. */
  7. var UI = module.exports = function (opt) {
  8. // Instantiate the Readline interface
  9. // @Note: Don't reassign if already present (allow test to override the Stream)
  10. if (!this.rl) {
  11. this.rl = readlineFacade.createInterface(_.extend({
  12. terminal: true
  13. }, opt));
  14. }
  15. this.rl.resume();
  16. this.onForceClose = this.onForceClose.bind(this);
  17. // Make sure new prompt start on a newline when closing
  18. this.rl.on('SIGINT', this.onForceClose);
  19. process.on('exit', this.onForceClose);
  20. };
  21. /**
  22. * Handle the ^C exit
  23. * @return {null}
  24. */
  25. UI.prototype.onForceClose = function () {
  26. this.close();
  27. console.log('\n'); // Line return
  28. };
  29. /**
  30. * Close the interface and cleanup listeners
  31. */
  32. UI.prototype.close = function () {
  33. // Remove events listeners
  34. this.rl.removeListener('SIGINT', this.onForceClose);
  35. process.removeListener('exit', this.onForceClose);
  36. // Restore prompt functionnalities
  37. this.rl.output.unmute();
  38. // Close the readline
  39. this.rl.output.end();
  40. this.rl.pause();
  41. this.rl.close();
  42. this.rl = null;
  43. };