write.js 754 B

1234567891011121314151617181920212223242526272829303132
  1. /* @flow */
  2. const MAX_STACK_DEPTH = 1000
  3. export function createWriteFunction (
  4. write: (text: string, next: Function) => boolean,
  5. onError: Function
  6. ): Function {
  7. let stackDepth = 0
  8. const cachedWrite = (text, next) => {
  9. if (text && cachedWrite.caching) {
  10. cachedWrite.cacheBuffer[cachedWrite.cacheBuffer.length - 1] += text
  11. }
  12. const waitForNext = write(text, next)
  13. if (waitForNext !== true) {
  14. if (stackDepth >= MAX_STACK_DEPTH) {
  15. process.nextTick(() => {
  16. try { next() } catch (e) {
  17. onError(e)
  18. }
  19. })
  20. } else {
  21. stackDepth++
  22. next()
  23. stackDepth--
  24. }
  25. }
  26. }
  27. cachedWrite.caching = false
  28. cachedWrite.cacheBuffer = []
  29. return cachedWrite
  30. }