napi-rs/examples/napi/wasi-worker-browser.mjs

41 lines
995 B
JavaScript
Raw Normal View History

import { instantiateNapiModuleSync, MessageHandler, WASI } from '@napi-rs/wasm-runtime'
2024-01-17 00:28:40 +09:00
import { Volume, createFsFromVolume } from '@napi-rs/wasm-runtime/fs'
const fs = createFsFromVolume(
Volume.fromJSON({
'/': null,
}),
)
const handler = new MessageHandler({
onLoad({ wasmModule, wasmMemory }) {
const wasi = new WASI({
fs,
2024-01-10 12:18:13 +09:00
print: function () {
// eslint-disable-next-line no-console
console.log.apply(console, arguments)
},
printErr: function() {
2024-01-10 12:18:13 +09:00
// eslint-disable-next-line no-console
console.error.apply(console, arguments)
},
})
return instantiateNapiModuleSync(wasmModule, {
childThread: true,
wasi,
overwriteImports(importObject) {
importObject.env = {
...importObject.env,
...importObject.napi,
...importObject.emnapi,
memory: wasmMemory,
}
},
})
},
})
2024-01-10 12:18:13 +09:00
globalThis.onmessage = function (e) {
handler.handle(e)
}