HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

How can I check if a value implements a stream in Node.js?

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptcheckstreamhowvalueimplementsnodecan

Problem

A Stream is an abstract interface for working with streaming data in Node.js. It is designed to support many different types of streams, such as readable, writable, and duplex streams.
While specifics differ from one type to another, there are also commonalities that can be used to type check for a stream. On top of that, these classes are well-defined and documented, so we can use that to our advantage to type check for a specific type of stream.
In the most general case, we can check if a value is a stream by checking if it is an object and has a pipe property that is a function.
A readable stream needs to have a _read function and a _readableState object. This is in addition to the general stream check, defined previously.
A writable stream needs to have a _write function and a _writableState object. This is in addition to the general stream check, defined previously.

Solution

import { createReadStream } from 'fs';

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

isStream(createReadStream('test.txt')); // true


In the most general case, we can check if a value is a stream by checking if it is an object and has a pipe property that is a function.
A readable stream needs to have a _read function and a _readableState object. This is in addition to the general stream check, defined previously.
A writable stream needs to have a _write function and a _writableState object. This is in addition to the general stream check, defined previously.
Finally, a duplex stream needs to match the conditions for both a readable and a writable stream, as defined previously.
> [!NOTE]
>

Code Snippets

import { createReadStream } from 'fs';

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

isStream(createReadStream('test.txt')); // true
import { createReadStream } from 'fs';

const isReadableStream = val =>
  val !== null &&
  typeof val === 'object' &&
  typeof val.pipe === 'function' &&
  typeof val._read === 'function' &&
  typeof val._readableState === 'object';

isReadableStream(createReadStream('test.txt')); // true
import { createWriteStream } from 'fs';

const isWritableStream = val =>
  val !== null &&
  typeof val === 'object' &&
  typeof val.pipe === 'function' &&
  typeof val._write === 'function' &&
  typeof val._writableState === 'object';

isWritableStream(createWriteStream('test.txt')); // true

Context

From 30-seconds-of-code: typecheck-nodejs-streams

Revisions (0)

No revisions yet.