高级前端
node
【Q354】在 node 中如何判断一个对象是 stream

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

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 357 (opens in a new tab)

Author 回答者: shfshanyue (opens in a new tab)

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

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

代码如下,摘自 is-stream (opens in a new tab): 一个周下载量两千万的 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";

鸭子判断?