You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

110 lines
2.1 KiB

var events = require('events');
var util = require('util');
14 years ago
function Stream() {
events.EventEmitter.call(this);
}
util.inherits(Stream, events.EventEmitter);
exports.Stream = Stream;
Stream.prototype.pipe = function(dest /* options, filter */) {
var source = this;
// parse arguments
var options, filter;
if (typeof arguments[1] == 'object') {
options = arguments[1];
filter = arguments[2];
} else {
filter = arguments[1];
}
14 years ago
function ondata(chunk) {
// FIXME shouldn't need to test writable - this is working around bug.
// .writable should not change before a 'end' event is fired.
if (dest.writable) {
if (false === dest.write(chunk)) source.pause();
}
}
if (!filter) {
source.on('data', ondata);
} else {
//
// TODO: needs tests
//
var wait = false;
var waitQueue = [];
function done () {
wait = false;
// Drain the waitQueue
if (dest.writable && waitQueue.length) {
wait = true;
filter(waitQueue.shift(), ondata, done);
}
}
source.on('data', function (d) {
if (wait) {
waitQueue.push(d);
source.pause();
} else {
wait = true;
filter(d, ondata, done);
}
});
}
14 years ago
function ondrain() {
if (source.readable) source.resume();
}
14 years ago
dest.on('drain', ondrain);
/*
* If the 'end' option is not supplied, dest.end() will be called when
* source gets the 'end' event.
*/
14 years ago
if (!options || options.end !== false) {
14 years ago
function onend() {
dest.end();
}
14 years ago
source.on('end', onend);
}
14 years ago
dest.on('close', function() {
source.removeListener('data', ondata);
dest.removeListener('drain', ondrain);
source.removeListener('end', onend);
});
/*
* Questionable:
*/
if (!source.pause) {
14 years ago
source.pause = function() {
source.emit('pause');
};
}
if (!source.resume) {
14 years ago
source.resume = function() {
source.emit('resume');
};
}
14 years ago
dest.on('pause', function() {
source.pause();
});
14 years ago
dest.on('resume', function() {
if (source.readable) source.resume();
});
};