Created
July 31, 2011 23:28
-
-
Save tralamazza/1117341 to your computer and use it in GitHub Desktop.
node.js bind() hack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Author: Daniel Tralamazza <tralamazza@gmail.com> | |
* | |
* Patch Socket for a before connect event. | |
* Important! You must require this module before anything else. | |
* | |
* Usage: | |
* | |
* var patch = require('./bind_hack'); | |
* var bind_f = process.binding('net').bind; | |
* patch(function(socket, remote_port) { | |
* console.log('Socket.fd=' + socket.fd + ', remote port=' + remote_port); | |
* bind_f(socket.fd, 11111, '127.0.0.2'); // put some random port | |
* }); | |
*/ | |
var timers = require('timers'); | |
var last_port = null; | |
var o_active = timers.active; | |
var net = require('net'); | |
var o_connect = net.Socket.prototype.connect; | |
net.Socket.prototype.connect = function() { | |
last_port = Number(arguments[0]); | |
o_connect.apply(this, arguments); | |
}; | |
module.exports = function(callback) { | |
timers.active = function(obj) { | |
if (arguments.callee.caller.name == 'doConnect') | |
callback(obj, last_port); | |
o_active(obj); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment