Binary & Stream

Use these when returning non-text payloads, large files, or custom generated data.

Full source

File: pwsh/tutorial/examples/9.3-Binary-Stream.ps1


<#
    Sample: Binary & Stream Responses
    Purpose: Demonstrate binary and streaming responses in a Kestrun server.
    File:    9.3-Binary-Stream.ps1
    Notes:   Shows file download and streaming with error handling.
#>
param(
    [int]$Port = 5000,
    [IPAddress]$IPAddress = [IPAddress]::Loopback
)
Initialize-KrRoot -Path $PSScriptRoot
# 1. Logging
New-KrLogger | Add-KrSinkConsole | Register-KrLogger -Name 'console' -SetAsDefault

# 2. Server
New-KrServer -Name 'Responses 9.3'

# 3. Listener
Add-KrEndpoint -IPAddress $IPAddress -Port $Port


# Finalize configuration
Enable-KrConfiguration

# Binary route: download file
Add-KrMapRoute -Pattern '/logo' -Verbs GET -ScriptBlock {
    $path = Resolve-KrPath -Path './Assets/wwwroot/files/kestrun.png' -KestrunRoot
    Write-KrLog -Level Information -Message 'Resolved path: {path}' -Values $path
    if (Test-Path -Path $path) {
        $bytes = [System.IO.File]::ReadAllBytes($path)
        Write-KrBinaryResponse -InputObject $bytes -ContentType 'image/png'
    } else {
        Write-KrErrorResponse -Message 'kestrun.png not found' -StatusCode 404
    }
}

# Stream route: stream text file
Add-KrMapRoute -Pattern '/stream' -Verbs GET -ScriptBlock {
    $path = Resolve-KrPath -Path './Assets/wwwroot/files/sample.txt' -KestrunRoot
    Write-KrLog -Level Information -Message 'Resolved path: {path}' -Values $path
    if (Test-Path $path) {
        $fs = [System.IO.File]::OpenRead($path)
        Write-KrStreamResponse -InputObject $fs -ContentType 'text/plain'
    } else {
        Write-KrErrorResponse -Message 'sample.txt not found' -StatusCode 404
    }
}

# Start the server
Start-KrServer -CloseLogsOnExit

Step-by-step

  1. Logging: Register console logger as default.
  2. Server: Create server named ‘Responses 9.3’.
  3. Listener: Listen on 127.0.0.1:5000.
  4. /logo: resolves file, reads all bytes, writes binary response.
  5. /stream: opens text file stream, writes via streaming helper.
  6. Error handling: returns error response if file missing.
  7. Enable configuration and start server.

Try it

curl http://127.0.0.1:5000/logo --output logo.png
curl http://127.0.0.1:5000/stream

PowerShell equivalents:

Invoke-WebRequest -Uri http://127.0.0.1:5000/logo -OutFile logo.png
Invoke-WebRequest -Uri http://127.0.0.1:5000/stream | Select -ExpandProperty Content

Example routes

# Logging
New-KrLogger | Add-KrSinkConsole | Register-KrLogger -Name 'console' -SetAsDefault

# Server
New-KrServer -Name 'Responses 9.3'

# Listener
Add-KrEndpoint -IPAddress '127.0.0.1' -Port 5000

# Enable configuration
Enable-KrConfiguration

# Binary route: download file
Add-KrMapRoute -Pattern '/logo' -Verbs GET -ScriptBlock {
    $path = Resolve-KrPath -Pattern 'Assets/wwwroot/files/sample.bin' -KestrunRoot -Test
    if (Test-Path $path) {
        $bytes = [System.IO.File]::ReadAllBytes($path)
        Write-KrBinaryResponse -InputObject $bytes -ContentType 'application/octet-stream'
    } else {
        Write-KrErrorResponse -Message 'sample.bin not found' -StatusCode 404
    }
}

# Stream route: stream text file
Add-KrMapRoute -Pattern '/stream' -Verbs GET -ScriptBlock {
    $path = Resolve-KrPath -Pattern 'Assets/wwwroot/files/sample.txt' -KestrunRoot -Test
    if (Test-Path $path) {
        $fs = [System.IO.File]::OpenRead($path)
        Write-KrStreamResponse -InputObject $fs -ContentType 'text/plain'
    } else {
        Write-KrErrorResponse -Message 'sample.txt not found' -StatusCode 404
    }
}

# Start the server
Start-KrServer

When to choose which

Scenario Helper
Small binary (< 1–2 MB) Write-KrBinaryResponse
Large file on disk Write-KrStreamResponse
Dynamically generated large data Create a memory or pipe stream and use Write-KrStreamResponse

Troubleshooting

Symptom Cause Fix
404 on file routes Sample files not present Ensure Assets files exist
Memory pressure Large file via binary helper Use Write-KrStreamResponse instead
Wrong content type Not set explicitly Pass correct -ContentType

References


Previous / Next

Previous: Structured (XML / YAML / CSV) Next: HTML Templates & Files