It doesn’t look like the SpiderMonkey jsshell provides a means to read stdin or write to stdout as a TypedArray
outside of a WASI build (e.g. for spidermonkey-wasm-rs; sm-wasi-demo), see https://hg.mozilla.org/mozilla-central/file/tip/js/src/shell/js.cpp#l6251.
The outgoing message is written to getMessage.txt and sendMesssge.txt with os.file.writeTypedArrayToFile()
once on the first postMessage()
then the while
loop does not appear to continue as subsequent postMessage()
calls do not modify the files. Nothing is written to err.txt. I’m getting “Invalid byte sequence” error in the plain text file when observing writes of Uint32Array
though I am able to isolate the JSON message.
When I include the environment variable JS_STDOUT=stdout.txt
this is written to this file
6,0,0,0 34,116,101,115,116,34
which is technically the correct output
let message = new TextDecoder().decode(new Uint8Array([34,116,101,115,116,34])); // '"test"'
let length = Uint32Array.of(message.length); // 6
Anybody have experience writing data to stdout in a SpiderMonkey shell script?
#!/usr/bin/env -S JS_STDERR=err.txt ./js --enable-top-level-await
// SpiderMonkey Native Messaging host (W.I.P.)
// guest271314 7-7-2023
function getMessage() {
const stdin = readline();
const data = new Uint8Array([...stdin].map((char) => char.charCodeAt(0)));
const length = data.subarray(0, 4);
os.file.writeTypedArrayToFile('length.txt', length);
os.file.writeTypedArrayToFile('getMessage.txt', data.subarray(4));
return data.subarray(4);
}
function sendMessage(message) {
const header = Uint32Array.from({
length: 4,
},
(_, index) => (message.length >> (index * 8)) & 0xff
);
os.file.writeTypedArrayToFile('sendMessage.txt', header);
print(header);
print(message);
}
function main() {
while (true) {
const message = getMessage();
sendMessage(message);
// break;
}
}
try {
main();
} catch (e) {
quit();
}