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?
Streams are objects that allows developers to read/write data to and from a source in a continuous manner. There are four main types of streams in Node. js; readable, writable, duplex and transform.
The object stream classes are ObjectInputStream and ObjectOutputStream . These classes implement ObjectInput and ObjectOutput , which are subinterfaces of DataInput and DataOutput . That means that all the primitive data I/O methods covered in Data Streams are also implemented in object streams.
stdout is a regular stream that can only deal with String s and Buffer s. If we want to be able to pipe our data to process. stdout , we need to create another object stream that appropriately transforms our data, for example, by emitting a JSON-stringified version of our object.
There are four fundamental stream types in Node. js: Readable, Writable, Duplex, and Transform streams. A readable stream is an abstraction for a source from which data can be consumed.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With