File tree Expand file tree Collapse file tree 3 files changed +46
-4
lines changed
Expand file tree Collapse file tree 3 files changed +46
-4
lines changed Original file line number Diff line number Diff line change 1+ var Stream = require ( 'stream' ) . Stream
2+ , util = require ( 'util' ) ;
3+
4+ var Collector = function ( ) {
5+ this . _bytesWritten = 0 ;
6+ this . _data = '' ;
7+ this . readable = true ;
8+ this . writable = true ;
9+ } ;
10+ util . inherits ( Collector , Stream ) ;
11+ Collector . prototype . write = function ( data ) {
12+ if ( typeof data == 'string' ) {
13+ this . _bytesWritten += Buffer . byteLength ( data ) ;
14+ } else {
15+ this . _bytesWritten += data . length ;
16+ }
17+
18+ this . _data += data . toString ( ) ;
19+
20+ this . emit ( 'data' , data ) ;
21+ } ;
22+ Collector . prototype . end = function ( data ) {
23+ if ( data ) { this . write ( data ) ; }
24+
25+ this . readable = false ;
26+ this . writable = false ;
27+ this . emit ( 'end' ) ;
28+ } ;
29+ Collector . prototype . getData = function ( ) {
30+ return this . _data ;
31+ } ;
32+ Collector . prototype . getBytesWritten = function ( ) {
33+ return this . _bytesWritten ;
34+ } ;
35+ module . exports = Collector ;
Original file line number Diff line number Diff line change @@ -11,7 +11,7 @@ LogStream.prototype.write = function(data) {
1111 this . emit ( 'data' , data ) ;
1212} ;
1313LogStream . prototype . end = function ( data ) {
14- if ( data ) { this . emit ( 'data' , data ) ; }
14+ if ( data ) { this . write ( data ) ; }
1515
1616 this . emit ( 'end' ) ;
1717} ;
Original file line number Diff line number Diff line change 11var Stream = require ( 'stream' ) ,
22 fs = require ( 'fs' ) ,
33 http = require ( 'http' ) ,
4- LogStream = require ( './logstream ' ) ;
4+ Collector = require ( './collector ' ) ;
55
66http . createServer ( function ( request , response ) {
7- var logstream = new LogStream ( ) ;
8- fs . createReadStream ( './large-file.txt' ) . pipe ( logstream ) . pipe ( response ) ;
7+ var collector = new Collector ( ) ;
8+ fs . createReadStream ( './large-file.txt' ) . pipe ( collector ) ;
9+ collector . on ( 'end' , function ( ) {
10+ response . writeHead ( 200 , {
11+ 'Content-Type' : 'text/plain' ,
12+ 'Content-Length' : collector . getBytesWritten ( )
13+ } ) ;
14+ response . end ( collector . getData ( ) ) ;
15+ } ) ;
916} ) . listen ( 8080 ) ;
1017
1118console . log ( 'Server listening on port 8080\n' ) ;
You can’t perform that action at this time.
0 commit comments