File tree Expand file tree Collapse file tree 2 files changed +20
-3
lines changed
Expand file tree Collapse file tree 2 files changed +20
-3
lines changed Original file line number Diff line number Diff line change @@ -171,8 +171,14 @@ PythonShell.prototype.send = function (message) {
171171PythonShell . prototype . receive = function ( data ) {
172172 var self = this ;
173173 var lines = ( '' + data ) . split ( / \n / g) ;
174- var lastLine = lines . pop ( ) ;
175174
175+ if ( lines . length === 1 ) {
176+ // an incomplete record, keep buffering
177+ this . _remaining = ( this . _remaining || '' ) + lines [ 0 ] ;
178+ return this ;
179+ }
180+
181+ var lastLine = lines . pop ( ) ;
176182 // fix the first line with the remaining from the previous iteration of 'receive'
177183 lines [ 0 ] = ( this . _remaining || '' ) + lines [ 0 ] ;
178184 // keep the remaining for the next iteration of 'receive'
@@ -184,14 +190,16 @@ PythonShell.prototype.receive = function (data) {
184190 self . emit ( 'message' , JSON . parse ( line ) ) ;
185191 } catch ( err ) {
186192 self . emit ( 'error' , extend (
187- new Error ( 'invalid JSON message: ' + data ) ,
188- { inner : err , data : data }
193+ new Error ( 'invalid JSON message: ' + data + ' >> ' + err ) ,
194+ { inner : err , data : line }
189195 ) ) ;
190196 }
191197 } else {
192198 self . emit ( 'message' , line ) ;
193199 }
194200 } ) ;
201+
202+ return this ;
195203} ;
196204
197205/**
Original file line number Diff line number Diff line change @@ -131,6 +131,15 @@ describe('PythonShell', function () {
131131 count . should . be . exactly ( 3 ) ;
132132 } ) . end ( done ) ;
133133 } ) ;
134+ it ( 'should properly buffer partial messages' , function ( done ) {
135+ var pyshell = new PythonShell ( 'echo_json.py' , {
136+ mode : 'json'
137+ } ) ;
138+ pyshell . on ( 'message' , function ( message ) {
139+ message . should . be . an . Object ;
140+ message . should . eql ( { a : true } ) ;
141+ } ) . receive ( '{"a"' ) . receive ( ':' ) . receive ( 'true}\n' ) . end ( done ) ;
142+ } ) ;
134143 it ( 'should not be invoked when mode is "binary"' , function ( done ) {
135144 var pyshell = new PythonShell ( 'echo_args.py' , {
136145 args : [ 'hello' , 'world' ] ,
You can’t perform that action at this time.
0 commit comments