Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

initial code

  • Loading branch information...
commit 3fcf43c41aa20987b10bdce6c90f53b41f4cd72c 1 parent 2ec5063
@polotek authored
Showing with 62 additions and 1 deletion.
  1. +14 −1 README.md
  2. +48 −0 index.js
View
15 README.md
@@ -1,4 +1,17 @@
data-collector-stream
=====================
-A read/write stream that collects data
+A read/write stream that collects data
+
+```
+var Stream = require('stream'),
+ fs = require('fs'),
+ Collector = require('./streams/collector');
+
+var collector = new Collector();
+fs.createReadStream('./large-file.txt').pipe(collector);
+collector.on('end', function() {
+ console.log(collector.getBytesWritten());
+ console.log(collector.getData());
+});
+```
View
48 index.js
@@ -0,0 +1,48 @@
+var Stream = require('stream').Stream
+ , util = require('util');
+
+var Collector = function() {
+ this._bytesWritten = 0;
+ this._data = null;
+ this.readable = true;
+ this.writable = true;
+};
+util.inherits(Collector, Stream);
+Collector.prototype.write = function(data) {
+ if(typeof data == 'string') {
+ if(!this._data) { this._data = ''; }
+ this._data += data.toString();
+ this._bytesWritten += Buffer.byteLength(data);
+ } else {
+ // Buffer
+ if(!this._data) { this._data = []; }
+ this._data.push(data);
+ this._bytesWritten += data.length;
+ }
+
+ this.emit('data', data);
+};
+Collector.prototype.end = function(data) {
+ if(data) { this.write(data); }
+
+ this.readable = false;
+ this.writable = false;
+
+ this.getData();
+ this.emit('end');
+};
+Collector.prototype.getData = function() {
+ if(this.writable) {
+ throw new Error('Cannot get data before the end of the stream');
+ }
+
+ if(Array.isArray(this._data)) {
+ this._data = Buffer.concat(this._data, this.getBytesWritten());
+ }
+
+ return this._data;
+};
+Collector.prototype.getBytesWritten = function() {
+ return this._bytesWritten;
+};
+module.exports = Collector;
Please sign in to comment.
Something went wrong with that request. Please try again.