Module: Ferrum::Page::Stream

Included in:
Ferrum::Page
Defined in:
lib/ferrum/page/stream.rb

Overview

Reads a CDP IO stream handle (e.g. from Page.printToPDF or Tracing.tracingComplete) in chunks and writes its contents to a file on disk or accumulates it in memory.

Constant Summary collapse

STREAM_CHUNK =
128 * 1024

Instance Method Summary collapse

Instance Method Details

#stream(output:, handle:) ⇒ void

This method returns an undefined value.

Reads a CDP IO stream in chunks, writing each chunk to the given output until the stream is exhausted.

Parameters:

  • output (#<<)

    Anything that responds to #<<, e.g. an open File or a String.

  • handle (String)

    The CDP IO stream handle to read from.



83
84
85
86
87
88
89
90
91
# File 'lib/ferrum/page/stream.rb', line 83

def stream(output:, handle:)
  loop do
    result = command("IO.read", handle: handle, size: STREAM_CHUNK)
    chunk = result.fetch("data")
    chunk = Base64.decode64(chunk) if result["base64Encoded"]
    output << chunk
    break if result["eof"]
  end
end

#stream_to(path:, encoding:, handle:) ⇒ Boolean, String

Reads a CDP IO stream to a file on disk, or into memory when no path is given.

Parameters:

  • path (String, nil)

    The path to save the stream's contents to. When nil the contents are returned in memory instead.

  • encoding (Symbol)

    :base64 or :binary. Only used when path is nil.

  • handle (String)

    The CDP IO stream handle to read from.

Returns:

  • (Boolean, String)

    true when saved to disk, otherwise the stream's contents.



30
31
32
33
34
35
36
# File 'lib/ferrum/page/stream.rb', line 30

def stream_to(path:, encoding:, handle:)
  if path.nil?
    stream_to_memory(encoding: encoding, handle: handle)
  else
    stream_to_file(path: path, handle: handle)
  end
end

#stream_to_file(path:, handle:) ⇒ Boolean

Reads a CDP IO stream and writes its contents to a file on disk.

Parameters:

  • path (String)

    The path to save the stream's contents to.

  • handle (String)

    The CDP IO stream handle to read from.

Returns:

  • (Boolean)


49
50
51
52
# File 'lib/ferrum/page/stream.rb', line 49

def stream_to_file(path:, handle:)
  File.open(path, "wb") { |f| stream(output: f, handle: handle) }
  true
end

#stream_to_memory(encoding:, handle:) ⇒ String

Reads a CDP IO stream into memory.

Parameters:

  • encoding (Symbol)

    :base64 to Base64-encode the result, :binary to return it as is.

  • handle (String)

    The CDP IO stream handle to read from.

Returns:

  • (String)


65
66
67
68
69
# File 'lib/ferrum/page/stream.rb', line 65

def stream_to_memory(encoding:, handle:)
  data = String.new # Mutable string has << and compatible to File
  stream(output: data, handle: handle)
  encoding == :base64 ? Base64.encode64(data) : data
end