Reputation: 123
I can't seem to override net.Socket.write. The example below is not my real use case, but rather a scaled down, runnable example to demonstrate the issue.
const net = require("net");
class UTF8Socket extends net.Socket {
constructor () {
super();
this.setEncoding("utf8");
}
write(data, cb) {
console.log("Sending...");
super.write(data, "utf8", cb);
}
end(data) {
console.log("Ending socket...");
super.end(data);
}
}
// Setup server
const server = net.createServer(socket => {
socket.setEncoding("utf8");
socket.on("data", (res) => console.log("Server received data:", res));
});
server.listen(8080, '127.0.0.1');
// Create a UTF8Socket and write to server
const socket = new UTF8Socket();
socket.connect(8080, "127.0.0.1", () => {
socket.write("test write\n");
socket.end("test end");
});
Expected output:
Sending...
Ending socket...
Server received data: test write
test end
Actual output:
Ending socket...
Server received data: test write
test end
The overridden end function is called as you can see from the output, but only the original net.Socket.write is ever called. I feel like I'm missing something...
Upvotes: 0
Views: 440
Reputation: 203474
I guess it's because of this code in the implementation of net.Socket.connect()
:
if (this.write !== Socket.prototype.write)
this.write = Socket.prototype.write;
Possible workaround:
connect() {
let result = super.connect.apply(this, arguments);
this.write = UTF8Socket.prototype.write.bind(this);
return result;
}
Upvotes: 2