WebAssembly

    For host environments like the web browser and nodejs, build as a dynamic library using the freestanding OS target. Here’s an example of running Zig code compiled to WebAssembly with nodejs.

    math.zig

    Shell

    1. const fs = require('fs');
    2. const source = fs.readFileSync("./math.wasm");
    3. const typedArray = new Uint8Array(source);
    4. WebAssembly.instantiate(typedArray, {
    5. env: {
    6. print: (result) => { console.log(`The result is ${result}`); }
    7. }}).then(result => {
    8. const add = result.instance.exports.add;
    9. add(1, 2);
    10. });

    Shell

    WASI

    Zig’s support for WebAssembly System Interface (WASI) is under active development. Example of using the standard library and reading command line arguments:

    args.zig

    1. var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
    2. const gpa = general_purpose_allocator.allocator();
    3. const args = try std.process.argsAlloc(gpa);
    4. defer std.process.argsFree(gpa, args);
    5. for (args) |arg, i| {
    6. std.debug.print("{}: {s}\n", .{ i, arg });
    7. }
    8. }
    1. $ zig build-exe args.zig -target wasm32-wasi

    Shell

    A more interesting example would be extracting the list of preopens from the runtime. This is now supported in the standard library via std.fs.wasi.PreopenList:

    preopens.zig

    1. const std = @import("std");
    2. const PreopenList = std.fs.wasi.PreopenList;
    3. pub fn main() !void {
    4. var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
    5. const gpa = general_purpose_allocator.allocator();
    6. var preopens = PreopenList.init(gpa);
    7. defer preopens.deinit();
    8. try preopens.populate();
    9. for (preopens.asSlice()) |preopen, i| {
    10. std.debug.print("{}: {}\n", .{ i, preopen });
    11. }
    12. }

    Shell