Skip to content

Core\Http\Stream::saveTo

$stream->saveTo(string $path, uint $max): void$stream->saveTo(
    string $path,
    uint $max,
): void

Writes the body of a streamed reply straight to a file, as the bytes arrive.

The program never holds the whole body in memory, so it can save a download that is larger than its memory. The second value is the largest size you accept, in bytes. It is required, because the other server decides how large the reply is.

saveTo() throws a RuntimeError when the body is larger than that limit. It throws an IOError when a file already exists at the path, so an existing file is never replaced. After a failed save, the part already written is deleted.

A program you start from the command line may save to any path. On a server, a program may write only in the folders that Core\IO::createTemporaryDirectory made for it. Any other path needs the fs.write capability.

The body of a stream can be read only once. After saveTo(), a call to chunks(), lines(), events() or saveTo() on the same stream throws a LogicError.

The examples below save a report, stop a download that is too large, and run a backup job that never replaces a file.

Parameters

  • $pathstringThe file to write. Nothing may exist at the path yet. This method cannot replace a file. The overwrite option of Core\IO::writeStream can.
  • $maxuintThe largest number of bytes to accept. It is required, because the server chooses the length of the reply, and the bytes use disk space.

Return value

Returns void. Nothing. When writing fails part of the way through, the partial file is deleted before the error is thrown. So nobody later finds an incomplete file.

Errors

  • LogicErrorThe body of this stream has already been read. The error message names the method that read it.
  • RuntimeErrorThe configuration does not allow fs.write for this path, or the body is longer than max bytes.
  • IOErrorSomething is already at the path, or the operating system could not create or write the file.

Examples

Saving a download to a file

<?nvs
// Shows how to save the body of a streamed reply to a file.
// This server sends a small CSV report.
Core\Test::answerHttp('https://reports.example.com/sales.csv', 200, { body: "day,total\nmon,120\ntue,95\n" });
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'sales.csv');
Core\Http\Stream $report = Core\Http\Client::openStream(Core\Http\Method::Get, 'https://reports.example.com/sales.csv');
// `saveTo` writes the body to `$path`. The second value is the largest size you accept, in bytes.
$report->saveTo($path, 1000000);
// This prints "saved 25 bytes" and then the three lines of the file.
echo 'saved ', Core\IO::size($path), " bytes\n";
echo Core\IO::read($path);
Output
saved 25 bytes
day,total
mon,120
tue,95

A download that is too large

<?nvs
// Shows what happens when a download is larger than the size you allow.
// This server sends 5000 bytes. The program allows at most 1000.
Core\Test::answerHttp('https://images.example.com/photo.jpg', 200, { body: Core\Str::repeat('x', 5000) });
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'photo.jpg');
Core\Http\Stream $photo = Core\Http\Client::openStream(Core\Http\Method::Get, 'https://images.example.com/photo.jpg');
// `saveTo` throws a `RuntimeError` when the body is larger than the limit.
try {
$photo->saveTo($path, 1000);
echo "the photo was saved\n";
} catch (RuntimeError $error) {
echo "the photo is too large\n";
}
// The part that was already written is deleted. This prints "file exists: no".
echo 'file exists: ', Core\IO::exists($path) ? 'yes' : 'no', "\n";
Output
the photo is too large
file exists: no

A nightly backup that is never replaced

<?nvs
// Shows a nightly job that downloads a backup. It checks the status first, and it never replaces a backup it saved before.
Core\Test::answerHttp('https://backup.example.com/export/2024-05-01', 200, { body: Core\Str::repeat("row\n", 300) });
class Backup
{
public static function save(string $url, string $path): void
{
Core\Http\Stream $download = Core\Http\Client::openStream(Core\Http\Method::Get, $url);
if ($download->status() != 200) {
echo 'the server sent status ', $download->status(), "\n";
return;
}
try {
// At most 50 MB. A backup larger than that is an error.
$download->saveTo($path, 50000000);
echo 'saved ', Core\IO::size($path), " bytes\n";
} catch (IOError $error) {
// `saveTo` throws an `IOError` when a file already exists at `$path`.
echo "a backup for this day already exists\n";
}
}
}
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'backup-2024-05-01.txt');
// The job runs twice. This prints "saved 1200 bytes" and then "a backup for this day already exists".
Backup::save('https://backup.example.com/export/2024-05-01', $path);
Backup::save('https://backup.example.com/export/2024-05-01', $path);
Output
saved 1200 bytes
a backup for this day already exists