JavaScript/TypeScript harness for running QuickJS-NG in WASI reactor mode
This package provides a JavaScript/TypeScript implementation for running QuickJS-NG compiled to WebAssembly using the WASI reactor model. It includes a complete browser-compatible WASI shim and high-level API for JavaScript execution.
- QuickJS-NG - Upstream QuickJS-NG (includes WASI reactor build)
- go-quickjs-wasi-reactor - Go implementation with wazero
- go-quickjs-wasi - Go implementation for command model (blocking)
npm install quickjs-wasi-reactor
# or
bun add quickjs-wasi-reactorimport { loadQuickJS, buildFileSystem } from "quickjs-wasi-reactor";
// Load QuickJS from a URL or buffer
const qjs = await loadQuickJS("/path/to/qjs-wasi.wasm");
// Initialize with --std flag (provides std, os, bjson globals)
qjs.init(["qjs", "--std"]);
// Evaluate JavaScript code
qjs.eval(`console.log("Hello from QuickJS!")`);
// Run the event loop
await qjs.runLoop();
// Cleanup
qjs.destroy();// Basic runtime with std modules available for import
qjs.init();
qjs.eval(`import * as std from 'qjs:std'; std.printf("Hello\\n")`, true);
// With --std flag to expose std, os, bjson as globals
qjs.init(["qjs", "--std"]);
qjs.eval(`std.printf("Hello\\n")`); // std is already global
// With script args accessible via scriptArgs global
qjs.init(["qjs", "script.js", "--verbose"]);
qjs.eval(`console.log(scriptArgs)`); // ['qjs', 'script.js', '--verbose']import { loadQuickJS, buildFileSystem } from "quickjs-wasi-reactor";
// Build a virtual filesystem
const fs = buildFileSystem(
new Map([
["script.js", 'console.log("Hello from script!")'],
[
"lib/utils.js",
"export function greet(name) { return `Hello, ${name}!` }",
],
]),
);
const qjs = await loadQuickJS("/path/to/qjs-wasi.wasm", { fs });
qjs.init(["qjs", "--std"]);
qjs.eval(
`
import { greet } from './lib/utils.js'
console.log(greet('World'))
`,
true,
);
await qjs.runLoop();
qjs.destroy();Use preopens when QuickJS needs extra WASI roots in addition to /.
createReadOnlyMapMount is the simplest helper for immutable file trees, and
createReadOnlyMount accepts a caller-provided synchronous file lookup for
on-demand mounts.
import { loadQuickJS, createReadOnlyMapMount } from "quickjs-wasi-reactor";
const assets = createReadOnlyMapMount(
"/assets",
new Map([
["lib.js", 'export const greeting = "Hello from a preopen"'],
]),
);
const qjs = await loadQuickJS("/path/to/qjs-wasi.wasm", {
preopens: [assets],
});
qjs.init(["qjs", "--std"]);
qjs.eval(
`
import { greeting } from '/assets/lib.js'
console.log(greeting)
`,
true,
);
await qjs.runLoop();
qjs.destroy();import { loadQuickJS } from "quickjs-wasi-reactor";
const qjs = await loadQuickJS("/path/to/qjs-wasi.wasm", {
stdout: (line) => (document.body.innerHTML += `<p>${line}</p>`),
stderr: (line) => console.error("Error:", line),
onDevOut: (data) => {
// Handle binary data written to /dev/out
console.log("Received", data.length, "bytes");
},
});
qjs.init();
qjs.eval(`console.log("This goes to custom stdout")`);
await qjs.runLoop();
qjs.destroy();import { loadQuickJS, PollableStdin } from "quickjs-wasi-reactor";
const stdin = new PollableStdin();
const qjs = await loadQuickJS("/path/to/qjs-wasi.wasm", { stdin });
qjs.init(["qjs", "--std"]);
// Push data to stdin
qjs.pushStdin(new TextEncoder().encode("Hello from stdin\n"));
// Run the loop - QuickJS can read from stdin
await qjs.runLoop();
qjs.destroy();For fine-grained control over JavaScript execution, use loopOnce() instead of runLoop():
import { loadQuickJS, LOOP_IDLE, LOOP_ERROR } from "quickjs-wasi-reactor";
const qjs = await loadQuickJS("/path/to/qjs-wasi.wasm");
qjs.init(["qjs", "--std"]);
qjs.eval(`
os.setTimeout(() => console.log("timer fired"), 100)
console.log("scheduled timer")
`);
// Manual event loop - integrate with your own scheduling
while (true) {
const result = qjs.loopOnce();
if (result === LOOP_ERROR) throw new Error("JavaScript error");
if (result === LOOP_IDLE) break; // No more work
if (result === 0) {
// More microtasks pending - yield to browser then continue
await new Promise((r) => queueMicrotask(r));
} else if (result > 0) {
// Timer pending in N ms - do other work or wait
await new Promise((r) => setTimeout(r, result));
}
}
qjs.destroy();const qjs = await loadQuickJS("/path/to/qjs-wasi.wasm");
qjs.init(["qjs", "--std"]);
qjs.eval(`
let frame = 0
function tick() {
console.log("Frame:", frame++)
if (frame < 60) os.setTimeout(tick, 16)
}
tick()
`);
// Cooperative scheduling with browser
function runFrame() {
const result = qjs.loopOnce();
if (result >= 0) {
requestAnimationFrame(runFrame);
} else {
qjs.destroy();
}
}
requestAnimationFrame(runFrame);Load and create a QuickJS instance from a WASM source.
Parameters:
wasmSource: URL string,Response,ArrayBuffer, orUint8Arrayoptions: Optional configuration (seeQuickJSOptions)
Returns: Promise<QuickJS>
Create a QuickJS instance from a pre-compiled WebAssembly module.
Parameters:
wasmModule:WebAssembly.Moduleoptions: Optional configuration
Returns: QuickJS
| Option | Type | Default | Description |
|---|---|---|---|
args |
string[] |
['qjs'] |
WASI command-line arguments |
env |
string[] |
[] |
Environment variables (key=value) |
debug |
boolean |
false |
Enable WASI debug logging |
stdout |
(line: string) => void |
console.log |
Custom stdout line handler |
stderr |
(line: string) => void |
console.error |
Custom stderr line handler |
fs |
Map<string, File|Dir> |
new Map() |
Virtual filesystem root contents |
preopens |
Fd[] |
[] |
Additional preopened WASI roots |
onDevOut |
(data: Uint8Array) => void |
undefined |
Handler for /dev/out writes |
stdin |
PollableStdin |
new PollableStdin() |
Custom stdin source |
Initialize QuickJS runtime and context. Modules qjs:std, qjs:os, and qjs:bjson can be imported in evaluated code.
Pass ['qjs', '--std'] to expose std, os, and bjson as globals.
Supported flags:
--std- Load std, os, bjson modules as globals-m, --module- Treat script as ES module-e, --eval- Evaluate expression-I, --include- Include file before script
Evaluate JavaScript code.
code: JavaScript source codeisModule: Treat as ES module (default:false)filename: Filename for error messages (default:'<eval>')
Run one iteration of the event loop. Returns:
> 0: Next timer fires in N milliseconds0: More microtasks pending-1(LOOP_IDLE): No pending work-2(LOOP_ERROR): Error occurred
Run the event loop until idle. Yields to the browser event loop between iterations.
Returns: Promise<number> (exit code)
Run the event loop synchronously. Suitable for Node.js/Bun.
Returns: number (exit code)
Poll for I/O events and invoke handlers.
Push data to stdin for the QuickJS instance to read.
Check if stdin has data available.
Stop the event loop.
Destroy the QuickJS runtime and release resources.
Build a virtual filesystem from a map of paths to content.
const fs = buildFileSystem(
new Map([
["path/to/file.js", "content"],
["another/file.txt", new Uint8Array([1, 2, 3])],
]),
);Unlike the standard WASI "command" model that blocks in _start(), the reactor model exports functions for re-entrant execution:
Reactor Initialization (preferred):
qjs_init_argv(argc, argv)- Initialize with CLI args (sets up module loader)qjs_get_context()- Get JSContext* for use with other APIsqjs_destroy()- Cleanup reactor runtime
Evaluation:
JS_Eval(ctx, input, len, filename, flags)- Evaluate JavaScript codeJS_FreeValue(ctx, val)- Free a JSValue
Event Loop:
js_std_loop_once(ctx)- Run one event loop iteration (non-blocking)js_std_poll_io(ctx, timeout_ms)- Poll for I/O eventsjs_std_dump_error(ctx)- Dump exception to stderr
Memory:
malloc(size)/free(ptr)- Memory allocation
This enables re-entrant execution in JavaScript host environments where blocking is not possible.
MIT