Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs: Check if variable is readable stream

Tags:

node.js

How i can check if a var is a readable stream in Nodejs?

Example:

function foo(streamobj){

   if(streamobj != readablestream){
       // Error: no writable stream
   }else{
      // So something with streamobj 
   }
}

I tried

if (!(streamobj instanceof stream.Readable)){

But than i get a ReferenceError: stream is not defined

like image 657
mdunisch Avatar asked May 27 '14 08:05

mdunisch


1 Answers

Your problem is definitely that you haven't required stream. But. instanceof is not a good method to check if variable is a readable stream. Consider following cases:

  • object can be old-style stream (instance of stream.Stream);
  • object can be just emitter with data and end events;
  • object can be instance of Readable from external module (https://github.com/isaacs/readable-stream);

The best way to go is duck typing. Basically, if you are going to pipe stream, check if it has pipe method, if you are going to listen to events, check if stream has on method, etc.

like image 160
vkurchatkin Avatar answered Oct 25 '22 16:10

vkurchatkin