Skip to content

Commit aff308e

Browse files
committed
custom data collection stream
1 parent d7c413f commit aff308e

File tree

3 files changed

+46
-4
lines changed

3 files changed

+46
-4
lines changed

collector.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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;

logstream.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ LogStream.prototype.write = function(data) {
1111
this.emit('data', data);
1212
};
1313
LogStream.prototype.end = function(data) {
14-
if(data) { this.emit('data', data); }
14+
if(data) { this.write(data); }
1515

1616
this.emit('end');
1717
};

streams.js

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
11
var Stream = require('stream'),
22
fs = require('fs'),
33
http = require('http'),
4-
LogStream = require('./logstream');
4+
Collector = require('./collector');
55

66
http.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

1118
console.log('Server listening on port 8080\n');

0 commit comments

Comments
 (0)