Skip to content

Instantly share code, notes, and snippets.

@andy0130tw
Created November 25, 2023 09:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andy0130tw/63a3bf17c4ac0ae0717fb210f025ee16 to your computer and use it in GitHub Desktop.
Save andy0130tw/63a3bf17c4ac0ae0717fb210f025ee16 to your computer and use it in GitHub Desktop.
My WASI runtime wrapper template in Node.js (v20+)
import { readFile } from 'node:fs/promises'
import { WASI } from 'wasi'
import { argv, env } from 'node:process'
import * as path from 'node:path'
const wasmPath = path.resolve('/path/to/wasm/here.wasm')
const args = [path.basename(wasmPath), ...argv.slice(2)]
const wasi = new WASI({
version: 'preview1',
args,
env,
preopens: {
'/': '/',
},
returnOnExit: true,
})
console.log('Compiling...', wasmPath, args)
const wasm = await WebAssembly.compile(
await readFile(wasmPath),
)
const importObject = wasi.getImportObject()
if (importObject.wasi_unstable) {
importObject.wasi_snapshot_preview1 = importObject.wasi_unstable
}
console.log('Instantiating...')
const instance = await WebAssembly.instantiate(wasm, importObject)
console.log('Starting...')
const ret = wasi.start(instance)
console.log('Exited with code', ret)
process.exit(ret)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment