How to test if an object is a Stream in NodeJS

I have a function which receives an object that could be a string, Buffer or Stream.

I can easily test if the object is a Buffer like so: if (x instanceof Buffer)

What's the best way to test if an object is a Stream? There doesn't appear to be a Stream base class in node - is there?

What should I look for?

The prototype you are looking for is the stream.Readable stream for readable streams, and stream.Writable for writable streams. They work in the same way as when you check for Buffer.

For Readable you can do:

var stream = require('stream');

function isReadableStream(obj) {
  return obj instanceof stream.Stream &&
    typeof (obj._read === 'function') &&
    typeof (obj._readableState === 'object');
}

console.log(isReadableStream(fs.createReadStream('car.jpg'))); // true
console.log(isReadableStream({}))); // false
console.log(isReadableStream(''))); // false