@@ -314,22 +314,45 @@ Modem.prototype.buildPayload = function(err, isStream, statusCodes, openStdin, r
314314} ;
315315
316316Modem . prototype . demuxStream = function ( stream , stdout , stderr ) {
317- var header = null ;
318-
319- stream . on ( 'readable' , function ( ) {
320- header = header || stream . read ( 8 ) ;
321- while ( header !== null ) {
322- var type = header . readUInt8 ( 0 ) ;
323- var payload = stream . read ( header . readUInt32BE ( 4 ) ) ;
324- if ( payload === null ) break ;
325- if ( type == 2 ) {
326- stderr . write ( payload ) ;
327- } else {
328- stdout . write ( payload ) ;
317+ var nextDataType = null ;
318+ var nextDataLength = null ;
319+ var buffer = new Buffer ( '' ) ;
320+ function processData ( data ) {
321+ if ( data ) {
322+ buffer = Buffer . concat ( [ buffer , data ] ) ;
323+ }
324+ if ( ! nextDataType ) {
325+ if ( buffer . length >= 8 ) {
326+ var header = bufferSlice ( 8 ) ;
327+ nextDataType = header . readUInt8 ( 0 ) ;
328+ nextDataLength = header . readUInt32BE ( 4 ) ;
329+ // It's possible we got a "data" that contains multiple messages
330+ // Process the next one
331+ processData ( ) ;
332+ }
333+ } else {
334+ if ( buffer . length >= nextDataLength ) {
335+ var content = bufferSlice ( nextDataLength ) ;
336+ if ( nextDataType === 1 ) {
337+ stdout . write ( content ) ;
338+ } else {
339+ stderr . write ( content ) ;
340+ }
341+ nextDataType = null ;
342+ // It's possible we got a "data" that contains multiple messages
343+ // Process the next one
344+ processData ( ) ;
329345 }
330- header = stream . read ( 8 ) ;
331346 }
332- } ) ;
347+ }
348+
349+ function bufferSlice ( end ) {
350+ var out = buffer . slice ( 0 , end ) ;
351+ buffer = new Buffer ( buffer . slice ( end , buffer . length ) ) ;
352+ return out ;
353+ }
354+
355+ stream . on ( 'data' , processData ) ;
333356} ;
334357
335358Modem . prototype . followProgress = function ( stream , onFinished , onProgress ) {
0 commit comments