[英]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: 考虑以下情况:
stream.Stream
); stream.Stream
实例); data
and end
events; data
和end
事件的发射器; Readable
from external module ( https://github.com/isaacs/readable-stream ); 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.