non-intrusive logging of data over a socket

26 views
Skip to first unread message

Dave Horton

unread,
Oct 30, 2015, 1:45:35 PM10/30/15
to nodejs

is there any way to get an event from a net.socket when data is sent?  I have an app where I want to hand off a socket to a library, but then for debugging purposes I want to log everything sent or received over the socket by the library.  I'd rather not have to change the library, and I can register a 'data' handler to get the incoming data, but what about the outoing?

Jimb Esser

unread,
Oct 30, 2015, 4:17:42 PM10/30/15
to nodejs
Assuming "write" is the only function call that sends data (not sure if stream piping or anything calls something internal instead... in which case you'd want to use a "through" stream), you can hook that directly by overriding it on your instance of a socket, something like this should work:

var orig_write = socket.write;
socket.write = function(data) {
  this.emit.call(this, 'write', data);
  return orig_write.apply(this, arguments);
};

socket.on('write', function (data) {
  // yay
});

// pass socket on to library now

Hope this helps!
  Jimb
Reply all
Reply to author
Forward
0 new messages