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.
test.js
const fs = require('fs');
const source = fs.readFileSync("./math.wasm");
const typedArray = new Uint8Array(source);
WebAssembly.instantiate(typedArray, {
env: {
print: (result) => { console.log(`The result is ${result}`); }
}}).then(result => {
const add = result.instance.exports.add;
add(1, 2);
});
WASI
args.zig
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = &general_purpose_allocator.allocator;
const args = try std.process.argsAlloc(gpa);
defer std.process.argsFree(gpa, args);
for (args) |arg, i| {
std.debug.print("{}: {s}\n", .{ i, arg });
}
}
$ zig build-exe args.zig -target wasm32-wasi
preopens.zig
const std = @import("std");
const PreopenList = std.fs.wasi.PreopenList;
pub fn main() !void {
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = &general_purpose_allocator.allocator;
var preopens = PreopenList.init(gpa);
defer preopens.deinit();
try preopens.populate();
for (preopens.asSlice()) |preopen, i| {
std.debug.print("{}: {}\n", .{ i, preopen });
}
}