Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support onread in net #10753

Merged
merged 11 commits into from
May 5, 2024
20 changes: 19 additions & 1 deletion src/js/node/net.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@ const Socket = (function (InternalSocket) {
data({ data: self }, buffer) {
if (!self) return;

if (self.#onreadCallback) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (self.#onreadCallback) {
const onReadCallback = self.#onreadCallback;
if (onReadCallback) {
try {
onReadCallback(buffer.length, buffer);
} catch(e) {
self.emit("error", e);
}
return;
}

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally, we'd have a separate handlers object and not do this check here on every single call to onData

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed to use a separate handlers object

self.#onreadCallback(buffer.length, buffer);
return;
}

self.bytesRead += buffer.length;
const queue = self.#readQueue;

Expand Down Expand Up @@ -342,9 +347,10 @@ const Socket = (function (InternalSocket) {
pauseOnConnect = false;
#upgraded;
#unrefOnConnected = false;
#onreadCallback = null;

constructor(options) {
const { socket, signal, write, read, allowHalfOpen = false, ...opts } = options || {};
const { socket, signal, write, read, allowHalfOpen = false, onread = null, ...opts } = options || {};
super({
...opts,
allowHalfOpen,
Expand All @@ -359,6 +365,18 @@ const Socket = (function (InternalSocket) {
if (socket instanceof Socket) {
this.#socket = socket;
}
if (onread) {
if (typeof onread !== "object") {
throw new TypeError("onread must be an object");
}
if (typeof onread.callback !== "function") {
throw new TypeError("onread.callback must be a function");
}
this.#onreadCallback = onread.callback;
}
if (onread) {
console.log('using onread');
}

if (signal) {
signal.addEventListener("abort", () => this.destroy());
Expand Down