Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if an object is a Stream in NodeJS

Tags:

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?

like image 382
Mikuso Avatar asked Jun 09 '13 13:06

Mikuso


People also ask

Which object is a stream in node JS?

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.

Which object is a stream?

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.

Which object is a stream process stdout?

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.

Which is a valid stream in node?

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.


2 Answers

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 
like image 183
German Attanasio Avatar answered Sep 27 '22 18:09

German Attanasio


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

like image 43
Walter Avatar answered Sep 27 '22 20:09

Walter