0
0
mirror of https://github.com/nodejs/node.git synced 2024-11-30 07:27:22 +01:00
nodejs/lib/stream.js

71 lines
1.3 KiB
JavaScript
Raw Normal View History

2010-10-11 02:21:36 +02:00
var events = require('events');
var util = require('util');
2010-10-11 02:21:36 +02:00
function Stream () {
events.EventEmitter.call(this);
}
util.inherits(Stream, events.EventEmitter);
2010-10-11 02:21:36 +02:00
exports.Stream = Stream;
Stream.prototype.pipe = function (dest, options) {
var source = this;
function ondata (chunk) {
2010-11-24 03:30:52 +01:00
if (dest.writable) {
if (false === dest.write(chunk)) source.pause();
}
}
source.on("data", ondata);
2010-10-11 02:21:36 +02:00
function ondrain () {
2010-10-11 02:21:36 +02:00
if (source.readable) source.resume();
}
dest.on("drain", ondrain);
2010-10-11 02:21:36 +02:00
/*
* If the 'end' option is not supplied, dest.end() will be called when
* source gets the 'end' event.
*/
2010-10-11 07:05:49 +02:00
if (!options || options.end !== false) {
function onend () {
2010-10-11 02:21:36 +02:00
dest.end();
}
source.on("end", onend);
2010-10-11 02:21:36 +02:00
}
dest.on('close', function () {
2010-11-24 03:30:52 +01:00
source.removeListener('data', ondata);
dest.removeListener('drain', ondrain);
2010-11-24 03:30:52 +01:00
source.removeListener('end', onend);
});
2010-10-11 02:21:36 +02:00
/*
* Questionable:
*/
if (!source.pause) {
source.pause = function () {
source.emit("pause");
};
}
if (!source.resume) {
source.resume = function () {
source.emit("resume");
};
}
dest.on("pause", function () {
source.pause();
});
dest.on("resume", function () {
if (source.readable) source.resume();
});
};