Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Initial implementation and tests

  • Loading branch information...
commit 76e631081e1e7920b4f892ca553caa8acedadbaa 1 parent 7123e50
@felixge authored
Showing with 104 additions and 0 deletions.
  1. +1 −0  index.js
  2. +51 −0 lib/StreamCache.js
  3. +52 −0 test/test-with-child-processes.js
View
1  index.js
@@ -0,0 +1 @@
+module.exports = require('./lib/StreamCache');
View
51 lib/StreamCache.js
@@ -0,0 +1,51 @@
+var Util = require('util');
+var Stream = require('stream').Stream;
+
+module.exports = StreamCache;
+Util.inherits(StreamCache, Stream);
+function StreamCache() {
+ Stream.call(this);
+
+ this.writable = true;
+ this.readable = true;
+
+ this._buffers = [];
+ this._dests = [];
+ this._ended = false;
+}
+
+StreamCache.prototype.write = function(buffer) {
+ this._buffers.push(buffer);
+
+ this._dests.forEach(function(dest) {
+ dest.write(buffer);
+ });
+};
+
+StreamCache.prototype.pipe = function(dest, options) {
+ if (options) {
+ throw Error('StreamCache#pipe: options are not supported yet.');
+ }
+
+ this._buffers.forEach(function(buffer) {
+ dest.write(buffer);
+ });
+
+ if (this._ended) {
+ dest.end();
+ return dest;
+ }
+
+ this._dests.push(dest);
+
+ return dest;
+};
+
+StreamCache.prototype.end = function() {
+ this._dests.forEach(function(dest) {
+ dest.end();
+ });
+
+ this._ended = true;
+ this._dests = [];
+};
View
52 test/test-with-child-processes.js
@@ -0,0 +1,52 @@
+var StreamCache = require('..');
+var assert = require('assert');
+var spawn = require('child_process').spawn;
+
+var source = spawn('cat');
+var cache = new StreamCache();
+
+var dests = {};
+var dataEvents = {};
+['a', 'b', 'c'].forEach(function(name) {
+ var dest = dests[name] = spawn('cat');
+ dataEvents[name] = [];
+
+ dest.stdout.setEncoding('utf-8');
+ dest.stdout.on('data', function(chunk) {
+ dataEvents[name].push(chunk);
+ });
+});
+
+cache.pipe(dests.a.stdin);
+source.stdout.pipe(cache);
+source.stdin.write('Hello');
+
+source.stdout.once('data', function() {
+ cache.pipe(dests.b.stdin);
+
+ source.stdin.write('World');
+ source.stdin.end();
+});
+
+source.on('exit', function() {
+ cache.pipe(dests.c.stdin);
+});
+
+process.on('exit', function() {
+ var expected = ['Hello', 'World'];
+ var alternative = ['HelloWorld'];
+
+ assert.deepEqual(dataEvents.a, expected);
+
+ try{
+ assert.deepEqual(dataEvents.b, expected);
+ } catch (err) {
+ assert.deepEqual(dataEvents.b, alternative);
+ }
+
+ try{
+ assert.deepEqual(dataEvents.c, expected);
+ } catch (err) {
+ assert.deepEqual(dataEvents.c, alternative);
+ }
+});
Please sign in to comment.
Something went wrong with that request. Please try again.