readline.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. var readline = require('readline')
  2. var Promise = require('any-promise')
  3. var objectAssign = require('object-assign')
  4. var Interface = readline.Interface
  5. function wrapCompleter (completer) {
  6. if (completer.length === 2) return completer
  7. return function (line, cb) {
  8. var result = completer(line)
  9. if (typeof result.then !== 'function') {
  10. return cb(null, result)
  11. }
  12. result.catch(cb).then(function (result) {
  13. process.nextTick(function () { cb(null, result) })
  14. })
  15. }
  16. }
  17. function InterfaceAsPromised (input, output, completer, terminal) {
  18. if (arguments.length === 1) {
  19. var options = input
  20. if (typeof options.completer === 'function') {
  21. options = objectAssign({}, options, {
  22. completer: wrapCompleter(options.completer)
  23. })
  24. }
  25. Interface.call(this, options)
  26. } else {
  27. if (typeof completer === 'function') {
  28. completer = wrapCompleter(completer)
  29. }
  30. Interface.call(this, input, output, completer, terminal)
  31. }
  32. }
  33. InterfaceAsPromised.prototype = Object.create(Interface.prototype)
  34. InterfaceAsPromised.prototype.question = function (question, callback) {
  35. if (typeof callback === 'function') {
  36. return Interface.prototype.question.call(this, question, callback)
  37. }
  38. var self = this
  39. return new Promise(function (resolve) {
  40. Interface.prototype.question.call(self, question, resolve)
  41. })
  42. }
  43. objectAssign(exports, readline, {
  44. Interface: InterfaceAsPromised,
  45. createInterface: function (input, output, completer, terminal) {
  46. if (arguments.length === 1) {
  47. return new InterfaceAsPromised(input)
  48. }
  49. return new InterfaceAsPromised(input, output, completer, terminal)
  50. }
  51. })