23

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?

4

3 回答 3

13

Readable你可以这样做:

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
于 2015-02-17T14:42:58.580 回答
10

并非所有流都使用stream.Readableand实现stream.Writable

process.stdout instanceof require("stream").Writable; // false
process.stdout instanceof require("readable-stream").Writable; // false

更好的方法是单独检查read(), write(), end()功能。

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'
}

您可以随时参考:https ://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts#L252

于 2016-05-04T08:38:12.857 回答
8

您正在寻找的原型是stream.Readable可读流和stream.Writable可写流的流。它们的工作方式与您检查Buffer.

于 2013-06-09T13:27:43.587 回答