38 lines
1.4 KiB
JavaScript
38 lines
1.4 KiB
JavaScript
import { Bert } from "./bert.js";
|
|
import { Duplex } from "node:stream";
|
|
export class Port extends Duplex {
|
|
bert;
|
|
constructor(allBinariesAsString, mapKeyAsAtom, decodeUndefinedValues) {
|
|
super({ objectMode: true });
|
|
this.bert = new Bert(allBinariesAsString, mapKeyAsAtom, decodeUndefinedValues);
|
|
}
|
|
_read() {
|
|
const lenBytes = process.stdin.read(4);
|
|
if (lenBytes) {
|
|
const termLen = this.bert.bytesToInt(lenBytes, 4, true);
|
|
process.stderr.write(`Got term length: ${termLen}\n`);
|
|
const termBytes = process.stdin.read(termLen);
|
|
if (termBytes) {
|
|
this.push(this.bert.decode(termBytes));
|
|
}
|
|
else {
|
|
process.stderr.write(`Read should have gotten ${termLen} bytes.\n`);
|
|
}
|
|
}
|
|
}
|
|
_write(obj, encodingOrCallback, callback) {
|
|
const actualCallback = callback || typeof encodingOrCallback === "function" ? encodingOrCallback : undefined;
|
|
try {
|
|
const term = this.bert.encode(obj, true);
|
|
const len = Buffer.alloc(4);
|
|
len.writeUInt32BE(term.length, 0);
|
|
process.stdout.write(len);
|
|
return process.stdout.write(term, actualCallback);
|
|
}
|
|
catch (error) {
|
|
process.stderr.write(`Error writing: ${error}\n`);
|
|
return false;
|
|
}
|
|
}
|
|
}
|