Skip to content

Instantly share code, notes, and snippets.

@starstuck
Created October 4, 2018 14:59
Show Gist options
  • Save starstuck/590bcf819c38c0baa37177de091f5b48 to your computer and use it in GitHub Desktop.
Save starstuck/590bcf819c38c0baa37177de091f5b48 to your computer and use it in GitHub Desktop.
Monitor aync resources in node.js application
import asyncHooks from 'async_hooks';
const reservations = new Map();
asyncHooks.createHook({
init: function init(asyncId, type, triggerAsyncId) {
const e = {};
Error.captureStackTrace(e, init);
reservations.set(asyncId, {type, triggerAsyncId, stack: e.stack});
},
destroy: function destroy(asyncId) {
reservations.delete(asyncId);
}
}).enable();
const resources = () => {
const entries = new Map();
const root = ['process(1)'];
entries.set(1, root);
for (const [asyncId, {type, triggerAsyncId, stack}] of reservations.entries()) {
let parent = entries.get(triggerAsyncId);
if (!parent) {
parent = [`unknown(${triggerAsyncId})`];
entries.set(triggerAsyncId, parent);
root.push(parent);
}
const node = [`${type}(${asyncId})`, stack];
entries.set(asyncId, node);
parent.push(node);
}
return root;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment