napi-rs/examples/napi/wasi-worker-browser.mjs
LongYinan 46cbcf3ff1
feat(cli): allow sync fs operation between workers/mainThread (#2064)
* feat(cli): allow sync fs operation between workers/mainThread

* allow sync fs operation between workers/mainThread (#2065)

* Fix

* Update fixture

* flaky test

* Fix cross compile target

* Update zig

* macos-cross test was filtered

---------

Co-authored-by: Toyo Li <lifenglin314@outlook.com>
2024-04-23 12:14:06 +08:00

39 lines
1 KiB
JavaScript

import { instantiateNapiModuleSync, MessageHandler, WASI, createFsProxy } from '@napi-rs/wasm-runtime'
import { memfsExported as __memfsExported } from '@napi-rs/wasm-runtime/fs'
const fs = createFsProxy(__memfsExported)
const handler = new MessageHandler({
onLoad({ wasmModule, wasmMemory }) {
const wasi = new WASI({
fs,
preopens: {
'/': '/',
},
print: function () {
// eslint-disable-next-line no-console
console.log.apply(console, arguments)
},
printErr: function() {
// 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,
}
},
})
},
})
globalThis.onmessage = function (e) {
handler.handle(e)
}