Skip to content

downloadStream

downloadStream(options): Promise<ReturnType>

Defined in: packages/synapse-core/src/piece/download.ts:109

Download a piece from a URL as a stream, validating its PieceCID as the bytes flow through.

Memory use stays bounded regardless of the piece size, so this is the function to use for large pieces. The returned promise rejects for request errors (network, HTTP status, null body). Validation errors surface on the stream itself: every chunk is passed through as it arrives and, once the body ends, the stream errors with a DownloadPieceError instead of closing if the calculated PieceCID does not match expectedPieceCid or the body is empty. A body longer than the size encoded in expectedPieceCid errors as soon as it goes past that size.

Because the error only arrives after the last chunk, consumers that persist data (e.g. to a file) must treat the bytes as untrusted until the stream closes cleanly, and discard them on error.

Pass validate: false to skip validation, in which case expectedPieceCid is not needed.

Parameter Type Description
options OptionsType downloadStream.OptionsType

Promise<ReturnType>

A stream of the piece bytes downloadStream.ReturnType

Errors downloadStream.ErrorType

import * as Piece from '@filoz/synapse-core/piece'
const stream = await Piece.downloadStream({
  url: 'https://example.com/piece',
  expectedPieceCid: 'bafkzcib...',
})
for await (const chunk of stream) {
  console.log(chunk.length)
}