Running a separate program with spawn script
spawn script "adder.nvs" runs another file as a separate program, called a child. The child has
its own variables, static properties, memory and output. It starts at once. await waits for the
child to end and returns its result.
spawn script and await
spawn script "file.nvs" runs another file while your program keeps going. It gives you a handle. await $handle waits for that file and returns its result.
The result has four fields. ok is true when the file finished without an error. value is what the file returned, and you convert it with as. output is what the file printed, when you wrote output: "capture". error has the class name and the message when the file stopped with an error.
A path in quotes starts at the folder of the file that contains it. A path you build at run time must be a full path, or spawn script throws RuntimeError. Build one with Core\Path::join. You can also start a static method, written Class::method.
A static method and a file inside your application folder need no capability. A file outside that folder needs the script.spawn capability. You can await one handle once. A second await of the same handle throws LogicError.
Run another file and wait for it
<?nvs// Shows how to run another file and collect its result. `spawn script` starts// the file. `await` waits for it to finish and gives you a result to read.
// The path starts at the folder of this file.var $handle = spawn script 'jobs/count-rows.nvs' with(output: 'capture');
// The file is running now. Your program can do other work on this line.echo "the file was started\n";
var $result = await $handle;
// `ok` is true when the file finished without an error.echo 'ok: ', $result->ok ? 'true' : 'false', "\n";
// `value` is what the file returned. Convert it with `as`.int $rows = $result->value as int;echo 'rows: ', $rows, "\n";
// `output` is everything the file printed, because this spawn asked to keep it.echo 'it printed: ', $result->output;the file was startedok: truerows: 1200it printed: read the order fileTwo files at the same time
<?nvs// Shows two files running at the same time. Start both first, then wait for// both. The second file does not wait for the first one to finish.
// Each path starts at the folder of this file.var $prices = spawn script 'jobs/fetch-prices.nvs' with(output: 'capture');var $stock = spawn script 'jobs/fetch-stock.nvs' with(output: 'capture');
// Each `await` takes one handle. Wait for them in any order you like.var $gotPrices = await $prices;var $gotStock = await $stock;
int $found = ($gotPrices->value as int) + ($gotStock->value as int);echo 'prices said: ', $gotPrices->output;echo 'stock said: ', $gotStock->output;echo 'items to show: ', $found, "\n";prices said: prices are readystock said: stock is readyitems to show: 8Work on the page while the report is built
<?nvs// Shows why you start a file instead of calling a function. The report is built// while this program writes the page. Collect it at the end.
var $handle = spawn script 'jobs/build-report.nvs' with(output: 'capture');
// This part of the page is written while the report is still being built.echo "<h1>Sales</h1>\n";echo "<p>Numbers for last month.</p>\n";
var $report = await $handle;if ($report->ok) { tainted string $line = $report->value as string; echo '<p>', $line, "</p>\n";} else { echo "<p>The report is not ready.</p>\n";}<h1>Sales</h1><p>Numbers for last month.</p><p>Sales last month: 46500</p>Print the child s output and await once
<?nvs// Shows `output: "inherit"`. The child's output is printed when you `await` it.// A second `await` of the same handle throws `LogicError`.
var $hello = spawn script 'jobs/say-hello.nvs' with(output: 'inherit');echo "the parent prints first\n";
// The child's line is printed here, at the `await`.var $done = await $hello;echo 'ok: ', $done->ok ? 'true' : 'false', "\n";
try { var $again = await $hello;} catch (LogicError $e) { echo $e->message, "\n";}the parent prints firstthe child says hellook: true`await` was given a handle a previous `await` already collectedGive the child a value with arguments
<?nvs// Shows how to give a child a value with `arguments:`.
class Report{ public static function title(string $month, int $year): string { return 'Sales for ' . $month . ' ' . ($year as string); }}
// The child gets a copy of the array. A file reads it with `Core\Script::arguments()`.var $sum = await spawn script 'jobs/add-up.nvs' with(arguments: [10, 20, 30]);echo 'total: ', $sum->value as int, "\n";
// A static method gets the value as its arguments.// Each key of the array is the name of one parameter.var $report = await spawn script Report::title with(arguments: ['month' => 'July', 'year' => 2026]);echo $report->value as string, "\n";total: 60Sales for July 2026Details
spawn script gives a Core\Script\Handle. The handle has no properties, so $h->ok is E0405. await needs a handle. await $n on an int is E0401.
The entry is a path or a static method. An anonymous function is E0802.
with(…) takes the options arguments, limits, grants, output and on. Another name is E0101, and its help lists the five.
on: must be the word "worker" or "here", written at the spawn. Another word is E0818, and so is a variable. To choose the core while the program runs, write two spawns in an if.
output: may be a variable. A value that is not "capture" or "inherit" throws LogicError with the message `` spawn script's output: is 'capture' or 'inherit', got 'keep' ``.
The type of output in the result is Core\Html\Markup|Core\Cli\Text, not string. So string $s = $r->output; is E0401. echo $r->output works, and $r->output as string gives the text.
With output: "inherit", the child's output is printed when you await its handle. It comes after everything the parent printed before that await. The output field is then empty.
A handle that is never awaited prints nothing. The program ends when the parent ends, even while the child still runs.
value is mixed, so int $v = $r->value; is E0401. $r->value as string gives a tainted string. A child with no return gives null. A child that calls exit also gives null, and ok is true.
A child cannot return an object. When it does, ok is false, and the class in error is Error. This is true for an anonymous object too, and for a class the parent also declares.
arguments: copies its value at the spawn. A change the parent makes later is not seen by the child. Without arguments:, Core\Script::arguments() returns null. A file cannot receive an object in arguments:. The spawn then throws LogicError in the parent.
A static method gets each entry of arguments: as the argument with the same name. Write arguments: as an array with string keys, such as ["n" => 5]. Here an object can be passed. A method with parameters and no arguments: is E0402, and a key that names no parameter is E0486. When an entry is missing while the program runs, the spawn throws LogicError. When an entry has the wrong type, the child fails with a LogicError, and ok is false.
A path built while the program runs must be absolute. For a relative one, the message is ` spawn script needs an absolute path, and child.nvs is relative . A second line names Core\Path::join and Core\Path::fromWorkingDirectory`.
limits: { memory: "1M" } gives the child a memory limit. A child that goes over it ends with ok false and a RuntimeError. grants: [] gives the child no capabilities, so a spawn script inside it throws RuntimeError.
A child can start its own child. A task in Core\Task::all can start a child and await it.
A few options of with(...) are not shown above:
limits:sets lower limits for the child.grants:names the capabilities it may use. A child never gets more than its parent has.on: "worker"runs the child on another CPU core.on: "here"runs it on the core of the parent.outputis aCore\Html\Markupwhen the program writes HTML, and aCore\Cli\Textotherwise.
A child shares nothing
A script you start with spawn script runs on its own. It shares nothing with the program that started it.
Every class static in the started script begins at its declared value, whatever your program wrote in its own copy. A write inside the script stays there. Your own values are the same after the script has finished as they were before it began. Two scripts started one after another share nothing either.
Printing works the same way. With output: "capture" the text the script prints comes back to you in the output field of the result, and nothing reaches the screen. With output: "inherit" the script prints to your screen, and output is then empty.
The examples below show a script that cannot change your numbers, the two ways to handle what a script prints, and a health check made of three scripts that cannot disturb each other.
The script cannot change your data
<?nvs// Shows that a script you start with `spawn script` cannot change your data.// It gets its own copy of every class static, and your own copy stays as it is.
final class Orders{ public static int $counted = 0;}
Orders::$counted = 7;echo 'before: ', Orders::$counted, "\n";
// The path starts at the folder of this file.var $handle = spawn script 'scripts/count-orders.nvs' with(output: 'capture');var $result = await $handle;
// The script printed two lines while it ran. With `capture` they come back as// text. It read 0, because its own copy of `Orders::$counted` starts at 0.echo $result->output;
// The script set `Orders::$counted` to 42. This still prints 7.echo 'after: ', Orders::$counted, "\n";before: 7the script read 0the script wrote 42after: 7Keep what the script prints or show it
<?nvs// Shows the two ways to handle what a started script prints. A script has its// own place to print to. You decide where that text goes.
// `output: "capture"` keeps the text for you. Nothing reaches the screen while// the script runs. The path starts at the folder of this file.var $first = spawn script 'scripts/say-what-it-did.nvs' with(output: 'capture');var $kept = await $first;echo 'the script said: ', $kept->output;
// `value` is what the script returned. Convert it with `as`.int $files = $kept->value as int;echo 'it removed ', $files, " files\n";
// `output: "inherit"` sends the text to your own screen instead. All of it is// there once `await` has returned.var $second = spawn script 'scripts/say-what-it-did.nvs' with(output: 'inherit');var $shown = await $second;
// `output` is empty this time, because the text went to the screen.// `as string` converts it to a `string`, so `Core\Str::length` can count it.echo 'kept text: ', Core\Str::length($shown->output as string), " characters\n";the script said: removed 3 old filesit removed 3 filesremoved 3 old fileskept text: 0 charactersA health check of three scripts
<?nvs// Shows a health check made of three scripts. Each script has its own data. One// check cannot change what another check counted. This program adds the three// numbers up itself.
final class Report{ public static int $problems = 0;}
// `#[Core\Path]` says that a parameter is a file path. A relative path in// quotes passed to it starts at the folder of this file.class Here{ public static function path(#[Core\Path] string $path): string { return $path; }}
// `$dir` is a full path, so a path built from it works from any folder.string $dir = Here::path('checks');array<string> $checks = ['disk-space', 'mail-queue', 'old-sessions'];
foreach ($checks as string $name) { string $path = Core\Path::join($dir, $name . '.nvs'); var $handle = spawn script $path with(output: 'capture'); var $result = await $handle;
// All three scripts declare `Report::$problems` and start it at 0. The // number each one returns is its own count. int $problems = $result->value as int; Report::$problems = Report::$problems + $problems;
echo $name, ': ', $problems, " problem(s)\n"; echo ' ', $result->output;}
// This program added the three numbers up itself. The scripts could not.echo 'total: ', Report::$problems, " problem(s)\n";disk-space: 2 problem(s) two disks are above 90 percentmail-queue: 0 problem(s) the mail queue is emptyold-sessions: 1 problem(s) one session is older than a yeartotal: 3 problem(s)Details
A static property with an array value starts at its declared value in the child too. An entry the parent added is not there, and an entry the child adds does not reach the parent.
A child started with on: "here" runs on the same core as the parent. It shares nothing with the parent either.
A task in Core\Task::all can start a child. All tasks of the program share one value of each static property, but the child still gets its own copy.
The child is a separate program. It does not need the classes the parent declares, and it cannot read the parent's variables. A child that uses $x without declaring it does not compile. The error is E0301, and spawn script throws RuntimeError in the parent.
When the child fails
A script you start with spawn script runs on its own. When it fails, the failure comes back to you as a value.
await returns a result. ok is false when the script ended with an error it did not catch. error has the class name and the message of that error. output still has everything the script printed before it failed. Your program keeps running.
A mistake in your own program is different. A file name that points to nothing throws an error in your program. So does a file that does not compile, or a misspelled output: setting. Those errors happen at the line that starts the script, and you catch them with try.
The examples below show a failed script read as a result, your own mistake told apart from the script's failure, and a group of jobs where one fails and the other two still finish. The last one shows the error when your program may not start scripts.
The examples below run with this configuration file.
# Example 04 may not start a script. It shows the error a program gets then.# Without these lines, it may start any script in this folder.[[app]]entry = "04-without-the-grant.nvs"
[app.capabilities.script]spawn = falseA job that fails
<?nvs// Shows what you get when a script you started fails. `await` returns a result// with `ok` set to false, and `error` has the class name and the message.
// The path starts at the folder of this file.var $handle = spawn script 'jobs/import-orders.nvs' with(output: 'capture');var $result = await $handle;
echo 'ok: ', $result->ok ? 'true' : 'false', "\n";// `error` is empty when the script worked, so read it with `?->`.echo 'error: ', $result->error?->class, ': ', $result->error?->message, "\n";// The script printed this line before it failed. The failure did not lose it.echo 'output: ', $result->output;echo "this program is still running\n";ok: falseerror: RuntimeError: row 3 has no priceoutput: read 2 ordersthis program is still runningMy mistake or the scripts
<?nvs// Shows the two ways starting a script can go wrong. A mistake in this program// throws here. A failure inside the script comes back as a result.
// This file name points to nothing, so `spawn script` throws in this program.// Each path starts at the folder of this file.try { spawn script 'jobs/no-such-job.nvs';} catch (RuntimeError $mine) { echo "my mistake: there is no script at that path\n";}
// `output:` takes "capture" or "inherit". Any other word is a `LogicError`.try { spawn script 'jobs/import-orders.nvs' with(output: 'capturr');} catch (LogicError $typo) { echo 'my mistake: ', $typo->message, "\n";}
// This script starts, runs and then fails. That is a result, not a throw.var $handle = spawn script 'jobs/import-orders.nvs' with(output: 'capture');var $result = await $handle;echo 'the script failed: ', $result->error?->message, "\n";my mistake: there is no script at that pathmy mistake: `spawn script`'s `output:` is `'capture'` or `'inherit'`, got `'capturr'`the script failed: row 3 has no priceA nightly run of three jobs
<?nvs// Shows a program that runs three jobs and reports each one. The first job// fails, and the other two still run. This is what a nightly job runner does.
// `#[Core\Path]` says that a parameter is a file path. A relative path in// quotes passed to it starts at the folder of this file.class Here{ public static function path(#[Core\Path] string $path): string { return $path; }}
// `$jobs` is a full path, so a path built from it works from any folder.string $jobs = Here::path('jobs');array<string> $names = ['import-orders', 'build-invoices', 'send-receipts'];
int $failed = 0;foreach ($names as string $name) { string $path = Core\Path::join($jobs, $name . '.nvs'); var $handle = spawn script $path with(output: 'capture'); var $result = await $handle; // A failed job is a result you can read, so the loop goes on to the next. if ($result->ok) { echo $name, ": done\n"; } else { echo $name, ': failed, ', $result->error?->message, "\n"; $failed = $failed + 1; }}
echo $failed, " of 3 jobs failed\n";import-orders: failed, row 3 has no pricebuild-invoices: donesend-receipts: done1 of 3 jobs failedWithout the grant
<?nvs// Shows what happens when this program may not start scripts. Its `nvs.toml`// sets `spawn = false`, so `spawn script` throws a `RuntimeError`.
// The path starts at the folder of this file. The script never runs.try { var $handle = spawn script 'jobs/send-receipts.nvs'; var $result = await $handle;} catch (RuntimeError $denied) { // The message goes on with the full path of the script. // `Core\Str::before` keeps only the text before it. echo Core\Str::before($denied->message, ' for '), "\n";}echo "this program is still running\n";`spawn script` needs the capability `script.spawn`this program is still runningDetails
The type of error is null|{ class: string, message: string }. It is null when ok is true. So $r->error->message is E0459. Read it with ?->, or test $r->error != null first.
error has two fields, class and message. It has no backtrace and no line. $r->error?->line compiles, and throws a RuntimeError when it runs: ` $shape{class,message} has no field line `.
class is the name of the class the child threw. For a class the child declares itself, such as ImportFailed, the result has that name. A RecursionError in the child gives the class RecursionError and the message the call stack is too deep. A division by zero gives ArithmeticError.
A failure in the child never throws in the parent. A try around await catches nothing, and ok is false. With output: "inherit", what the child printed is printed at await, and then ok is false too.
A child that calls exit(3) gives ok true and error null. The result has no status number.
A missing file and a file that does not compile give the same message in the parent: ` spawn script '<path>': <path> could not be compiled; see the errors above . The compiler's errors are printed to standard error. For a missing file, that is a could not read` line with the message of the operating system.
Without the grant, the message is ` spawn script needs the capability script.spawn for <path>, which is not granted . A second line starts with help: and names [capabilities.script] in nvs.toml`.
Do and don’t
Section titled “Do and don’t”- Do use
spawn scriptfor work that must not share anything with your program. - Do check
okbefore you usevalue. - Do pass data with
arguments:and return data withreturn. - Don’t use
spawn scriptonly to run two calls at once. A task is cheaper.
