import { Bert } from "./bert.js"; import { Duplex } from "node:stream"; const bert = new Bert(); let termLen; let termBin; const fakeWrite = () => undefined; process.stdout.write = fakeWrite; export class Port extends Duplex { constructor() { super({ objectMode: true }); } _read() { { let term; if (termLen === undefined && null !== (termBin = process.stdin.read(4))) { termLen = bert.bytesToInt(termBin, 4, true); } if (termLen !== undefined && null !== (term = process.stdin.read(termLen))) { termLen = undefined; this.push(bert.decode(term)); } } } _write(obj, _encoding, callback) { let term; try { term = bert.encode(obj, true); } catch (error) { console.error(error); process.exit(1); } const len = Buffer.alloc(4); len.writeUInt32BE(term.length, 0); process.stdout.write = this._write; process.stdout.write(len); process.stdout.write(term, callback); process.stdout.write = fakeWrite; } // When all the data is done passing, it stops. _final() { this.push(null); } }