Skip to content

Instantly share code, notes, and snippets.

@dhbloo
Created December 16, 2024 09:44
Show Gist options
  • Save dhbloo/2e08e65392713dd88d4e321fc63aff89 to your computer and use it in GitHub Desktop.
Save dhbloo/2e08e65392713dd88d4e321fc63aff89 to your computer and use it in GitHub Desktop.
Example code to communicate with rapfi WASM module
<head>
<!-- Change this file name to the actual JS file name. -->
<script src="rapfi-multi.js"></script>
</head>
<body>
<input type="text" id="incommand" size="80" onkeydown="keydown()" />
<input type="button" value="SendCommand" onclick="sendCommand()" />
<input type="button" value="Terminate" onclick="terminate()" />
<br />
<textarea id="output" readonly rows="50" cols="120"> </textarea>
<script>
var rapfi = null;
var input = document.getElementById("incommand");
var output = document.getElementById("output");
function add_output(text) {
output.value += text + "\n";
output.scrollTop = output.scrollHeight;
}
function instantiateWasmMemory(isShared) {
return new WebAssembly.Memory({
initial: 256 * ((1024 * 1024) / 65536), // 128MB
maximum: 1024 * ((1024 * 1024) / 65536), // 1GB
shared: isShared,
});
}
Rapfi({
onReceiveStdout: add_output,
onReceiveStderr: add_output,
onExit: (c) => add_output("[Exited] " + c),
setStatus: (s) => add_output("[Status] " + s),
wasmMemory: instantiateWasmMemory(true),
}).then(function (instance) {
add_output("[Engine is initialized.]");
rapfi = instance;
});
function sendCommand(value) {
add_output("input> " + input.value);
rapfi.sendCommand(input.value);
input.value = "";
}
function terminate() {
add_output("[Terminate]");
try {
rapfi.terminate();
} catch (e) {
add_output("[Terminate Result] " + e.message);
}
}
function keydown() {
if (event.key === "Enter") sendCommand();
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment