From 86433979c6f33f78035011b3a4aa29c26b1e9c67 Mon Sep 17 00:00:00 2001 From: isaacs Date: Sun, 24 Feb 2013 22:14:30 -0800 Subject: [PATCH] stream: Writables are not pipe()able This handles the fact that stream.Writable inherits from the Stream class, meaning that it has the legacy pipe() method. Override that with a pipe() method that emits an error. Ensure that Duplex streams ARE still pipe()able, however. Since the 'readable' flag on streams is sometimes temporary, it's probably better not to put too much weight on that. But if something is an instanceof Writable, rather than of Readable or Duplex, then it's safe to say that reading from it is the wrong thing to do. Fix #3647 --- lib/_stream_writable.js | 5 +++++ test/simple/test-stream2-writable.js | 26 ++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index 9a5e7f02f8..b8f88be270 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -111,6 +111,11 @@ function Writable(options) { Stream.call(this); } +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function() { + this.emit('error', new Error('Cannot pipe. Not readable.')); +}; + // Override this method or _write(chunk, cb) Writable.prototype.write = function(chunk, encoding, cb) { var state = this._writableState; diff --git a/test/simple/test-stream2-writable.js b/test/simple/test-stream2-writable.js index 4cd37fd822..efd49021bb 100644 --- a/test/simple/test-stream2-writable.js +++ b/test/simple/test-stream2-writable.js @@ -21,6 +21,7 @@ var common = require('../common.js'); var W = require('_stream_writable'); +var D = require('_stream_duplex'); var assert = require('assert'); var util = require('util'); @@ -285,3 +286,28 @@ test('encoding should be ignored for buffers', function(t) { var buf = new Buffer(hex, 'hex'); tw.write(buf, 'binary'); }); + +test('writables are not pipable', function(t) { + var w = new W(); + w._write = function() {}; + var gotError = false; + w.on('error', function(er) { + gotError = true; + }); + w.pipe(process.stdout); + assert(gotError); + t.end(); +}); + +test('duplexes are pipable', function(t) { + var d = new D(); + d._read = function() {}; + d._write = function() {}; + var gotError = false; + d.on('error', function(er) { + gotError = true; + }); + d.pipe(process.stdout); + assert(!gotError); + t.end(); +});