diff --git a/index.js b/index.js index ffdd86a..b51bebc 100644 --- a/index.js +++ b/index.js @@ -250,31 +250,48 @@ function createFastCGIHandler(options) { } }); + var stdoutPushEvent = new EventEmitter(); + function stdoutPush(data) { - var toResume = (stdoutBuffer.length == 0); if(data === null) { stdoutToEnd = true; } else { stdoutBuffer = Buffer.concat([stdoutBuffer, Buffer.from(data)]); } - if(toResume) emulatedStdout.resume(); + stdoutPushEvent.emit("ready"); + emulatedStdout.resume(); + } + + function stdoutRead(n, callback) { + if(stdoutBuffer.length == 0 && stdoutToEnd) { + callback(Buffer.alloc(0)); + } else if(n != 0) { + var handler = function() { + if(n > stdoutBuffer.length && !stdoutToEnd) { + stdoutPushEvent.once("ready", handler); + fs.writeFileSync("/tmp/fai", ""); + } else { + var bytesToPush = Math.min(stdoutBuffer.length, n); + var bufferToPush = stdoutBuffer.subarray(0, bytesToPush); + stdoutBuffer = stdoutBuffer.subarray(bytesToPush); + callback(bufferToPush); + } + }; + handler(); + } } var stdoutBuffer = Buffer.alloc(0); var stdoutToEnd = false; var emulatedStdout = new stream.Readable({ read: function (n) { - if(stdoutBuffer.length == 0 && stdoutToEnd) { - this.push(null); - } else if (stdoutBuffer.length != 0 && n != 0) { - var bytesToPush = Math.min(stdoutBuffer.length, n); - var bufferToPush = stdoutBuffer.subarray(0, bytesToPush); - stdoutBuffer = stdoutBuffer.subarray(bytesToPush); - this.push(bufferToPush); - } + var s = this; + stdoutRead(n, function(buffer) { + s.push(buffer.length > 0 ? buffer : null); + }); } }); - emulatedStdout.pause(); + emulatedStdout.pause(); //Reduce backpressure var emulatedStderr = new stream.Readable({ read: function () {}