noderl/dist/main.js

38 lines
1.4 KiB
JavaScript
Raw Normal View History

2024-01-28 15:45:09 +00:00
import { Bert } from "./bert.js";
2024-01-28 11:32:24 +00:00
import { Duplex } from "node:stream";
export class Port extends Duplex {
2024-01-28 15:39:03 +00:00
bert;
2024-01-28 15:45:09 +00:00
constructor(allBinariesAsString, mapKeyAsAtom, decodeUndefinedValues) {
2024-01-28 11:32:24 +00:00
super({ objectMode: true });
2024-01-28 15:45:09 +00:00
this.bert = new Bert(allBinariesAsString, mapKeyAsAtom, decodeUndefinedValues);
2024-01-28 11:32:24 +00:00
}
2024-01-28 15:12:30 +00:00
_read() {
2024-01-28 15:01:33 +00:00
const lenBytes = process.stdin.read(4);
if (lenBytes) {
2024-01-28 15:39:03 +00:00
const termLen = this.bert.bytesToInt(lenBytes, 4, true);
process.stderr.write(`Got term length: ${termLen}\n`);
2024-01-28 15:01:33 +00:00
const termBytes = process.stdin.read(termLen);
if (termBytes) {
2024-01-28 15:39:03 +00:00
this.push(this.bert.decode(termBytes));
2024-01-28 11:32:24 +00:00
}
2024-01-28 15:01:33 +00:00
else {
process.stderr.write(`Read should have gotten ${termLen} bytes.\n`);
2024-01-28 11:32:24 +00:00
}
}
}
2024-01-28 15:12:30 +00:00
_write(obj, encodingOrCallback, callback) {
2024-01-28 15:01:33 +00:00
const actualCallback = callback || typeof encodingOrCallback === "function" ? encodingOrCallback : undefined;
2024-01-28 11:32:24 +00:00
try {
2024-01-28 15:39:03 +00:00
const term = this.bert.encode(obj, true);
2024-01-28 15:01:33 +00:00
const len = Buffer.alloc(4);
len.writeUInt32BE(term.length, 0);
process.stdout.write(len);
return process.stdout.write(term, actualCallback);
2024-01-28 11:32:24 +00:00
}
catch (error) {
2024-01-28 15:01:33 +00:00
process.stderr.write(`Error writing: ${error}\n`);
return false;
2024-01-28 11:32:24 +00:00
}
}
}