noderl/dist/main.js

37 lines
1.2 KiB
JavaScript

import { Duplex } from "node:stream";
export class Port extends Duplex {
bert;
constructor(bert) {
super({ objectMode: true });
this.bert = bert;
}
_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;
}
}
}