noderl/dist/main.js

41 lines
1.3 KiB
JavaScript

import { Bert } from "./bert.js";
import { Duplex } from "node:stream";
const bert = new Bert();
const fakeWrite = () => undefined;
process.stdout.write = fakeWrite;
export class Port extends Duplex {
constructor() {
super({ objectMode: true });
}
_read() {
const lenBytes = process.stdin.read(4);
if (lenBytes) {
const termLen = bert.bytesToInt(lenBytes, 4, true);
const termBytes = process.stdin.read(termLen);
if (termBytes) {
return bert.decode(termBytes);
}
else {
process.stderr.write(`Read should have gotten ${termLen} bytes.\n`);
return null;
}
}
else
return null;
}
_write(obj, encodingOrCallback, callback) {
const actualCallback = callback || typeof encodingOrCallback === "function" ? encodingOrCallback : undefined;
try {
const term = 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;
}
}
}