1010 * Module dependencies.
1111 */
1212
13- var Stream = require ( 'stream' ) . Stream ;
13+ var Readable = require ( 'stream' ) . Readable ;
14+ var util = require ( 'util' ) ;
1415
1516/**
1617 * Initialize a `JPEGStream` with the given `canvas`.
@@ -30,33 +31,43 @@ var Stream = require('stream').Stream;
3031 */
3132
3233var JPEGStream = module . exports = function JPEGStream ( canvas , options , sync ) {
33- var self = this
34- , method = sync
34+ if ( ! ( this instanceof JPEGStream ) ) {
35+ throw new TypeError ( "Class constructors cannot be invoked without 'new'" ) ;
36+ }
37+
38+ Readable . call ( this ) ;
39+
40+ var self = this ;
41+ var method = sync
3542 ? 'streamJPEGSync'
3643 : 'streamJPEG' ;
3744 this . options = options ;
3845 this . sync = sync ;
3946 this . canvas = canvas ;
40- this . readable = true ;
47+
4148 // TODO: implement async
4249 if ( 'streamJPEG' == method ) method = 'streamJPEGSync' ;
43- process . nextTick ( function ( ) {
44- canvas [ method ] ( options . bufsize , options . quality , options . progressive , function ( err , chunk ) {
45- if ( err ) {
46- self . emit ( 'error' , err ) ;
47- self . readable = false ;
48- } else if ( chunk ) {
49- self . emit ( 'data' , chunk ) ;
50- } else {
51- self . emit ( 'end' ) ;
52- self . readable = false ;
53- }
54- } ) ;
55- } ) ;
56- } ;
5750
58- /**
59- * Inherit from `EventEmitter`.
60- */
51+ // For now we're not controlling the c++ code's data emission, so we only
52+ // call canvas.streamPNGSync once and let it emit data at will.
53+ var hasStarted = false ;
54+
55+ self . _read = function ( ) {
56+ if ( ! hasStarted ) {
57+ hasStarted = true ;
58+ process . nextTick ( function ( ) {
59+ canvas [ method ] ( options . bufsize , options . quality , options . progressive , function ( err , chunk ) {
60+ if ( err ) {
61+ self . emit ( 'error' , err ) ;
62+ } else if ( chunk ) {
63+ self . push ( chunk ) ;
64+ } else {
65+ self . push ( null ) ;
66+ }
67+ } ) ;
68+ } ) ;
69+ }
70+ } ;
71+ } ;
6172
62- JPEGStream . prototype . __proto__ = Stream . prototype ;
73+ util . inherits ( JPEGStream , Readable ) ;
0 commit comments