极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。

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

Issue

欢迎在 Gtihub 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: 11/27/2021, 6:11:48 PM