Menu

Reference / Async

readFile()

function
function readFile(string $path, int $chunk = 1048576): string

Read a whole file in chunks, yielding to other tasks between them.

A big read does not hold the loop for its full duration: after each chunk the task gives other tasks a turn, so a 64 MB file stalls others for about 2 ms at a time instead of 15-25 ms. It is cancellation-aware: a cancelled task stops at the next chunk boundary with CancelledException instead of reading the rest.

Parameters

$path string
the file to read
$chunk int = 1048576
bytes per read; default 1 MiB

Returns

string — the file's contents, or '' when it cannot be opened

Throws

CancelledException
when the task is cancelled between chunks

See also: writeFile

View source