Skip to content

Core\IO::writeStream

Core\IO::writeStream(
    string $path,
    array<bytes>|Iterable<bytes>|Iterator<bytes> $src,
    {max?: uint, overwrite?: bool},
): void

Writes a file from many small pieces of data, one piece at a time.

Core\IO::writeStream takes a path and a list of bytes pieces, called chunks. It writes them in order. The list can be an array<bytes> or an iterator that makes each chunk when it is needed. Only one chunk is in memory at a time, so a large upload needs little memory.

The option max is the largest number of bytes the file may have. Bigger data throws a RuntimeError. The option overwrite is false by default. Then an existing file throws an IOError and is not changed.

When a write fails part of the way through, writeStream deletes the file before it throws. No half-written file stays on the disk.

A command-line program may write any path. On a server, a program may write only in the folders from Core\IO::createTemporaryDirectory. Any other path needs the fs.write capability. Without it, writeStream throws a RuntimeError and creates no file.

Parameters

  • $pathstringThe file to write. It must not already exist unless overwrite says otherwise.
  • $srcarray<bytes>|Iterable<bytes>|Iterator<bytes>The chunks, in order: an array<bytes>, an Iterable<bytes> or an Iterator<bytes>. Each chunk is written and then freed, so memory use does not grow with the length of the source.

Options

  • maxuintoptionalThe most bytes to accept across the whole stream. When it is not given, there is no limit. Nothing else limits the size of a file on disk, so this is the only limit.
  • overwritebooloptionalWhether an existing file may be replaced. It is false by default, because the file name usually comes from a client.

Return value

Returns void. Nothing. If a write fails part-way through, the partial file is removed before the error is thrown. So a later reader never finds a partial file that looks complete.

Errors

  • RuntimeErrorThe configuration does not grant fs.write for this path, or the stream ran past max bytes.
  • IOErrorSomething is already at the path and overwrite is false. Or the operating system did not allow the file to be created or written.

Examples

Write a file from chunks

<?nvs
// Shows how to write a file from a list of chunks with `Core\IO::writeStream`.
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'message.txt');
// Each chunk is a piece of the file. They are written in this order.
array<bytes> $chunks = ['Hello, ' as bytes, 'world' as bytes, "!\n" as bytes];
Core\IO::writeStream($path, $chunks);
// The file has all the chunks, one after the other. This prints "Hello, world!".
echo Core\IO::read($path);
Output
Hello, world!

Replace a file only when asked

<?nvs
// Shows that `Core\IO::writeStream` replaces an existing file only with the `overwrite` option.
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'avatar.png');
Core\IO::write($path, 'old picture');
array<bytes> $chunks = ['new picture' as bytes];
// The file already exists, so this throws an `IOError` and prints "already there".
try {
Core\IO::writeStream($path, $chunks);
} catch (IOError $e) {
echo 'already there', "\n";
}
// With `overwrite: true` the file is replaced. This prints "new picture".
Core\IO::writeStream($path, $chunks, { overwrite: true });
echo Core\IO::read($path), "\n";
Output
already there
new picture

Save an upload with a size limit

<?nvs
// Shows how a program saves an uploaded file and stops when the upload is too large.
string $dir = Core\Path::join(Core\IO::createTemporaryDirectory(), 'uploads');
Core\IO::makeDirectory($dir);
// An upload arrives in chunks. Here each chunk has 1000 bytes.
array<bytes> $small = [Core\Str::repeat('a', 1000) as bytes, Core\Str::repeat('b', 1000) as bytes];
array<bytes> $large = [];
uint $i = 0;
while ($i < 10) {
$large[] = Core\Str::repeat('c', 1000) as bytes;
$i = $i + 1;
}
// The limit is 5000 bytes. The small upload has 2000 bytes, so it is saved.
// This prints "small.bin: 2000 bytes".
Core\IO::writeStream(Core\Path::join($dir, 'small.bin'), $small, { max: 5000 });
echo 'small.bin: ', Core\IO::size(Core\Path::join($dir, 'small.bin')), ' bytes', "\n";
// The large upload has 10000 bytes. `writeStream` throws a `RuntimeError` and deletes
// the part it already wrote. This prints "too large" and "large.bin saved: false".
string $largePath = Core\Path::join($dir, 'large.bin');
try {
Core\IO::writeStream($largePath, $large, { max: 5000 });
} catch (RuntimeError $e) {
echo 'too large', "\n";
}
echo 'large.bin saved: ', Core\IO::exists($largePath) ? 'true' : 'false', "\n";
Output
small.bin: 2000 bytes
too large
large.bin saved: false