Alex W.'s Blog

How to work with streams in `got`

Updated:

Calling got.stream(url, options?) returns a duplex stream with additional events. This stream can be read from (e.g. listening to the data and end events) for retrieving the response body, and can be written to (e.g. calling write(data) and end()). If the stream is not read from then the response body will not be downloaded. The additional events expose request and response metadata (which can also be found on RequestEvents<T>):

.on('request', (r: http.ClientRequest) => ...) 
.on('redirect', (r: PlainResponse, nextOptions: NormalizedOptions) => ...)
.on('response', (r: PlainResponse) => ...) // This will not include the response body. If you want to download the response body you will need to listen to the `on('data')` and `.on('end')` events.
.on('uploadProgress' | 'downloadProgress', (p: Progress) => ...)

The events will be triggered loosely in the following order:

  1. Request
  2. Redirect
  3. Response
  4. Data
  5. DownloadProgress
  6. End

You can call destroy() on the stream to terminate the request at any time.