How to test if an object is a Stream in NodeJS

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

Not all streams are implemented using stream.Readable and stream.Writable.

process.stdout instanceof require("stream").Writable; // false
process.stdout instanceof require("readable-stream").Writable; // false

The better method is to individually check for the read(), write(), end() functions.

var EventEmitter = require("events");

function isReadableStream(test) {
    return test instanceof EventEmitter && typeof test.read === 'function'
}

function isWritableStream(test) {
    return test instanceof EventEmitter && typeof test.write === 'function' && typeof test.end === 'function'
}

You can always reffer to: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts#L252


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.

Tags:

Node.Js