Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bytecodealliance
GitHub Repository: bytecodealliance/wasmtime
Path: blob/main/docs/assemblyscript_demo/wasi-demo.ts
1690 views
1
/**
2
* WASI is enabled through asconfig.json in post 0.20.x versions of AssemblyScript.
3
* The module, @assemblyscript/wasi-shim is required to enable a WASI environment.
4
*
5
* This demo is meant to showcase some abilities of WASI utilized through the AssemblyScript language.
6
* It uses the latest version of AssemblyScript and will not work in older (<0.20.x) versions.
7
**/
8
9
// Import module that allows colors in the console as long as supported by WASI.
10
import { rainbow } from "as-rainbow/assembly";
11
12
// Call console.log which is overridden to use WASI syscalls by @assemblyscript/wasi-shim.
13
console.log(rainbow.blue(rainbow.boldMk("Hello from WasmTime WASI through AssemblyScript!")));
14
15
console.log(rainbow.boldMk("Press ctrl+c to exit this demo at any time."));
16
17
// Get the current time and print it.
18
console.log("\nWASI can read the system time and display it with the AssemblyScript Date API");
19
console.log(rainbow.boldMk("The current time is: ") + rainbow.italicMk(new Date(Date.now()).toString()));
20
21
// Read user input from process.stdin (API provided by AssemblyScript Wasi-Shim and WasmTime WASI API).
22
23
// Create a buffer to hold up to 100 characters of user input.
24
const buffer = new ArrayBuffer(100);
25
console.log("\nWASI can read user input from stdin. Write any word and return");
26
27
// Read data from stdin and write to buffer.
28
process.stdin.read(buffer);
29
30
// Print text and decode the buffer with String.UTF8.decode
31
console.log(rainbow.red("You said: " + String.UTF8.decode(buffer)))
32
33
waitForUserEnter("\nPlease press return to continue");
34
35
// Demonstrate the retrieval of cryptographically-safe random numbers through WASI.
36
console.log("WASI can fetch cryptographically-safe random numbers from the runtime\nSeries of random numbers:");
37
38
for (let i = 0; i < 5; i++) {
39
console.log(Math.random().toString());
40
}
41
42
// End
43
console.log(rainbow.red("\nThat's all! :D"));
44
45
function waitForUserEnter(text: string): void {
46
console.log(rainbow.italicMk(text));
47
const buf = new ArrayBuffer(1);
48
process.stdin.read(buf);
49
return;
50
}
51