Created
October 4, 2014 16:17
-
-
Save grncdr/0083571dd5f4fe867faf to your computer and use it in GitHub Desktop.
Sometimes it's hard to know who's keeping your process alive
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
var timeouts = []; | |
var intervals = []; | |
var sockets = []; | |
var setTimeout_ = setTimeout; | |
var clearTimeout_ = clearTimeout; | |
var setInterval_ = setInterval; | |
var clearInterval_ = clearInterval; | |
var Socket = require('net').Socket; | |
var emit = Socket.prototype.emit; | |
Socket.prototype.emit = function (event) { | |
if (event === 'connect') { | |
sockets.push(this); | |
} | |
else if (event === 'close') { | |
var self = this; | |
sockets = sockets.filter(function (socket) { return socket !== self }); | |
} | |
return emit.apply(this, arguments); | |
} | |
function forgetTimeout (timeout) { | |
timeouts = timeouts.filter(function (wrapper) { | |
return wrapper.timeout !== timeout; | |
}); | |
} | |
function getStack (type, time) { | |
var stack = new Error().stack.split('\n').slice(3).map(function (s) { return s.replace(/^\s+/, ''); }).join('\n') | |
return time + 'ms ' + type + ' created ' + stack; | |
} | |
global.setTimeout = function (fn, time) { | |
var timeout = setTimeout_.apply(this, arguments); | |
timeouts.push({ timeout: timeout, stack: getStack('timeout', time) }); | |
setTimeout_(forgetTimeout, time, timeout); | |
return timeout; | |
} | |
global.clearTimeout = function (timeout) { | |
forgetTimeout(timeout); | |
return clearTimeout_.apply(this, arguments); | |
} | |
global.setInterval = function (fn, time) { | |
var interval = setInterval_.apply(this, arguments); | |
intervals.push({ interval: interval, stack: getStack('interval', time) }); | |
return interval; | |
}; | |
global.clearInterval = function (interval) { | |
intervals = intervals.filter(function (wrapper) { | |
return wrapper.interval !== interval; | |
}); | |
return clearInterval_.apply(this, arguments); | |
} | |
module.exports = function report () { | |
return { | |
intervals: intervals.map(function (i) { return i.stack.split('\n') }), | |
timeouts: timeouts.map(function (i) { return i.stack.split('\n') }), | |
sockets: sockets.map(function (s) { return {local: s.localPort, remote: s.remotePort} }) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment