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

Issue

欢迎在 Issue 中交流与讨论: Issue 357

Author

回答者: shfshanyue

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

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

代码如下,摘自 is-stream: 一个周下载量两千万的 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: 6/28/2020, 4:58:35 PM