forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.js
50 lines (44 loc) · 1.48 KB
/
lib.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const SwiftRuntime = require("javascript-kit-swift").SwiftRuntime;
const WASI = require("@wasmer/wasi").WASI;
const WasmFs = require("@wasmer/wasmfs").WasmFs;
const promisify = require("util").promisify;
const fs = require("fs");
const readFile = promisify(fs.readFile);
const startWasiTask = async (wasmPath) => {
// Instantiate a new WASI Instance
const wasmFs = new WasmFs();
// Output stdout and stderr to console
const originalWriteSync = wasmFs.fs.writeSync;
wasmFs.fs.writeSync = (fd, buffer, offset, length, position) => {
const text = new TextDecoder("utf-8").decode(buffer);
switch (fd) {
case 1:
console.log(text);
break;
case 2:
console.error(text);
break;
}
return originalWriteSync(fd, buffer, offset, length, position);
};
let wasi = new WASI({
args: [],
env: {},
bindings: {
...WASI.defaultBindings,
fs: wasmFs.fs,
},
});
const swift = new SwiftRuntime();
// Fetch our Wasm File
const wasmBinary = await readFile(wasmPath);
// Instantiate the WebAssembly file
let { instance } = await WebAssembly.instantiate(wasmBinary, {
wasi_snapshot_preview1: wasi.wasiImport,
javascript_kit: swift.importObjects(),
});
swift.setInstance(instance);
// Start the WebAssembly WASI instance!
wasi.start(instance);
};
module.exports = { startWasiTask };