stream-head
v3.0.0
Published
Peek the first couple of bytes from a stream
Downloads
71,690
Readme
stream-head
This package allows for inspecting the first n bytes from a stream. A kind of "POSIX head(1)
for JavaScript".
It handles both Node.js streams and Whatwg streams (the Web Streams API used in browsers).
This package provides TypeScript types.
Versions
From v3:
- This package is a pure ESM, no CommonJS support
API
The default (and only) exported function takes a readable stream and returns a new readable stream stream
of the same type as the input stream, together with head
of type Uint8Array
. The old stream must not be used anymore, it will be piped to the returned stream. The returned stream will contain everything from the input stream, the first n bytes will be copied to the returned buffer, not consumed. If the stream doesn't contain n bytes, head
will be smaller. If the combined chunks up until n are larger than n, then head
will be larger than n too (it's not truncated).
If the stream is a Node.js ReadableStream it must not be in object-mode but rather transport Node.js Buffers (or typed arrays), and if the stream is a Whatwg ReadableStream, the chunks in the stream (at least up until n bytes) must be typed arrays (such as e.g. Uint8Array), ArrayBuffers or DataViews.
import streamHead from 'stream-head'
inputStream; // We get this from somewhere
// Peek the first 64 bytes from the stream.
const { stream, head } = await streamHead( inputStream, { bytes: 64 } );
stream; // The new stream (don't use inputStream anymore!)
head; // A Uint8Array with the first *at least* 64 bytes (or less if the stream was smaller)
For TypeScript
In tsconfig.json, lib
needs to include "DOM"
and types
need to include "node"
because this package support both DOM ReadableStream
and Node.js' NodeJS.ReadableStream
type.