Path: blob/main/docs/assemblyscript_demo/wasi-demo.ts
1690 views
/**1* WASI is enabled through asconfig.json in post 0.20.x versions of AssemblyScript.2* The module, @assemblyscript/wasi-shim is required to enable a WASI environment.3*4* This demo is meant to showcase some abilities of WASI utilized through the AssemblyScript language.5* It uses the latest version of AssemblyScript and will not work in older (<0.20.x) versions.6**/78// Import module that allows colors in the console as long as supported by WASI.9import { rainbow } from "as-rainbow/assembly";1011// Call console.log which is overridden to use WASI syscalls by @assemblyscript/wasi-shim.12console.log(rainbow.blue(rainbow.boldMk("Hello from WasmTime WASI through AssemblyScript!")));1314console.log(rainbow.boldMk("Press ctrl+c to exit this demo at any time."));1516// Get the current time and print it.17console.log("\nWASI can read the system time and display it with the AssemblyScript Date API");18console.log(rainbow.boldMk("The current time is: ") + rainbow.italicMk(new Date(Date.now()).toString()));1920// Read user input from process.stdin (API provided by AssemblyScript Wasi-Shim and WasmTime WASI API).2122// Create a buffer to hold up to 100 characters of user input.23const buffer = new ArrayBuffer(100);24console.log("\nWASI can read user input from stdin. Write any word and return");2526// Read data from stdin and write to buffer.27process.stdin.read(buffer);2829// Print text and decode the buffer with String.UTF8.decode30console.log(rainbow.red("You said: " + String.UTF8.decode(buffer)))3132waitForUserEnter("\nPlease press return to continue");3334// Demonstrate the retrieval of cryptographically-safe random numbers through WASI.35console.log("WASI can fetch cryptographically-safe random numbers from the runtime\nSeries of random numbers:");3637for (let i = 0; i < 5; i++) {38console.log(Math.random().toString());39}4041// End42console.log(rainbow.red("\nThat's all! :D"));4344function waitForUserEnter(text: string): void {45console.log(rainbow.italicMk(text));46const buf = new ArrayBuffer(1);47process.stdin.read(buf);48return;49}5051