简体   繁体   English

nodejs:检查变量是否为可读流

[英]nodejs: Check if variable is readable stream

How i can check if a var is a readable stream in Nodejs? 我如何检查var是否是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 但是我得到一个ReferenceError:没有定义流

Your problem is definitely that you haven't required stream . 你的问题肯定是你没有要求stream But. 但。 instanceof is not a good method to check if variable is a readable stream. instanceof不是检查变量是否为可读流的好方法。 Consider following cases: 考虑以下情况:

  • object can be old-style stream (instance of stream.Stream ); object可以是old-style stream( stream.Stream实例);
  • object can be just emitter with data and end events; 对象可以只是dataend事件的发射器;
  • object can be instance of Readable from external module ( https://github.com/isaacs/readable-stream ); object可以是来自外部模块的Readable实例( 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. 基本上,如果你要去pipe流,检查它是否有pipe方法,如果你要监听事件,检查流是否有on方法等。

It seems that you forgot to require the stream core module. 您似乎忘了要求流核心模块。

var stream = require('stream');

// somewhere in the file
if (!(streamobj instanceof stream.Readable)) {
    // Your logic
}

Make sure you do: 确保你这样做:

var stream = require('stream');

The function could be something like: 该功能可能是这样的:

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

Use is-stream package for that: 使用is-stream包:

 var isStream = require('is-stream'); if (isStream.readable(myStream)) { do(); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM