bufferizedPTY.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. module.exports = function patchPTYModule (path) {
  2. const mod = require(path)
  3. const oldSpawn = mod.spawn
  4. if (mod.patched) {
  5. return mod
  6. }
  7. mod.patched = true
  8. mod.spawn = (file, args, opt) => {
  9. let terminal = oldSpawn(file, args, opt)
  10. let timeout = null
  11. let buffer = ''
  12. let lastFlush = 0
  13. let nextTimeout = 0
  14. const maxWindow = 250
  15. const minWindow = 50
  16. function flush () {
  17. if (buffer) {
  18. terminal.emit('data-buffered', buffer)
  19. }
  20. lastFlush = Date.now()
  21. buffer = ''
  22. }
  23. function reschedule () {
  24. if (timeout) {
  25. clearTimeout(timeout)
  26. }
  27. nextTimeout = Date.now() + minWindow
  28. timeout = setTimeout(() => {
  29. timeout = null
  30. flush()
  31. }, minWindow)
  32. }
  33. terminal.on('data', data => {
  34. buffer += data
  35. if (Date.now() - lastFlush > maxWindow) {
  36. flush()
  37. } else {
  38. if (Date.now() > nextTimeout - (minWindow / 10)) {
  39. reschedule()
  40. }
  41. }
  42. })
  43. return terminal
  44. }
  45. return mod
  46. }