noderl/dist/main.js

41 lines
1.3 KiB
JavaScript
Raw Normal View History

2024-01-28 11:32:24 +00:00
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 });
}
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) {
const termLen = bert.bytesToInt(lenBytes, 4, true);
const termBytes = process.stdin.read(termLen);
if (termBytes) {
return 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`);
return null;
2024-01-28 11:32:24 +00:00
}
}
2024-01-28 15:01:33 +00:00
else
return null;
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:01:33 +00:00
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);
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
}
}
}