zachmz35
zachmz35
CDCloudflare Developers
Created by zachmz35 on 10/13/2024 in #workers-help
Preloading Emscripten-generated JS module in a Worker
I'm having issues preloading a JS/WASM library in a CF Worker - the JS library starts as C++ and then gets transpiled to JS with Emscripten and CMake. I'm transpiling with ES6_SYNTAX and MODULARIZED enabled. I include this JS/WASM library sparks.js into the Cloudflare Worker project which I called hello-wrangler. Below is my index.ts in the hello-wrangler project. I do the imports and then I call loadModule() in a useEffect in hopes to have the module load proactively. It should be available for any route or action. I'm trying to setup an action on localhost:8787/ to print out the module instance, libptr. I always end up with the null condition, return c.text("No libptr");
import { Hono } from 'hono';
import { useEffect, useState } from 'hono/jsx';

// The JS/C++ library Module and Lib class
import Module from './sparks';
import { Lib } from './sparks';

const [libptr, setLibptr] = useState<Lib | null>(null);

const loadModule = async (): Promise<void> => {
const activeModule = await Module();
if (activeModule) {
let inst = activeModule.Lib.get_instance("Lib", 1.0);
if (inst) {
setLibptr(inst);
inst.description = "Updated from JS";
inst.version = 2.2;
console.log(inst.to_str());
} else {
console.error("Failed to create Lib instance");
}
} else {
console.error("Failed to load Module");
}
}

useEffect(() => {
// Load module on page mount
loadModule();

return () => {
libptr.delete();
}
}
}, []);

const app = new Hono<{ Bindings: Bindings }>();

app.use('/', async c => {
if (libptr) {
return c.text(`libptr:\n\t${libptr.to_str()}`);
} else {
// Always prints out this response
return c.text("No libptr");
}

});

export default app;
import { Hono } from 'hono';
import { useEffect, useState } from 'hono/jsx';

// The JS/C++ library Module and Lib class
import Module from './sparks';
import { Lib } from './sparks';

const [libptr, setLibptr] = useState<Lib | null>(null);

const loadModule = async (): Promise<void> => {
const activeModule = await Module();
if (activeModule) {
let inst = activeModule.Lib.get_instance("Lib", 1.0);
if (inst) {
setLibptr(inst);
inst.description = "Updated from JS";
inst.version = 2.2;
console.log(inst.to_str());
} else {
console.error("Failed to create Lib instance");
}
} else {
console.error("Failed to load Module");
}
}

useEffect(() => {
// Load module on page mount
loadModule();

return () => {
libptr.delete();
}
}
}, []);

const app = new Hono<{ Bindings: Bindings }>();

app.use('/', async c => {
if (libptr) {
return c.text(`libptr:\n\t${libptr.to_str()}`);
} else {
// Always prints out this response
return c.text("No libptr");
}

});

export default app;
One thing I already tried to do is to add await loadModule() which did not succeed (instead got 500 error). Thanks.
2 replies