# 在 node 中如何判断一个对象是 stream

Issue

欢迎在 Issue 中交流与讨论: Issue 357 (opens new window)

stream 可以通过缓冲区来高效利用内存,从而提高性能。常用场景如读写大文件、http-server 中的大静态文件渲染。

每一个 stream 都有 pipe 函数,可以用来判断一个对象是否 stream

代码如下,摘自 is-stream (opens new window): 一个周下载量两千万的 npm package。

const isStream = stream =>
	stream !== null &&
	typeof stream === 'object' &&
	typeof stream.pipe === 'function';

isStream.writable = stream =>
	isStream(stream) &&
	stream.writable !== false &&
	typeof stream._write === 'function' &&
	typeof stream._writableState === 'object';

isStream.readable = stream =>
	isStream(stream) &&
	stream.readable !== false &&
	typeof stream._read === 'function' &&
	typeof stream._readableState === 'object';

isStream.duplex = stream =>
	isStream.writable(stream) &&
	isStream.readable(stream);

isStream.transform = stream =>
	isStream.duplex(stream) &&
	typeof stream._transform === 'function' &&
	typeof stream._transformState === 'object';
Last Updated: 1/17/2021, 2:02:56 PM