Node.js: inspect what's left in the event loop that's preventing the script from exiting naturally

node.js

node.js Problem Overview


Node.js script won't exit if there's callbacks left in the main event loop. While one could forcefully terminate the script by calling process.exit() or throwing exceptions, it is recommended to let the script terminate "naturally", by always doing proper cleanup. However, this sometimes can be difficult as bugs in the code may prevent proper cleanup, e.g., I may forget to remove an IntervalObject when no longer needed, etc., which eventually prevents the program from terminating.

Therefore, is there a way to debug a non-terminating script to find out what's remaining registered in the event loop? In other words, is there a way in Node.js to debug what's preventing the program from exiting?

node.js Solutions


Solution 1 - node.js

You can call process._getActiveRequests() to get a list of active I/O requests and process._getActiveHandles() to get a list of open handles/file descriptors.

Solution 2 - node.js

The wtfnode package utilizes the tools mentioned by @mscdex but presents in a more developer-friendly way. I highly recommend this for tracking down these annoyances.

const wtf = require('wtfnode');

// ...

wtf.dump();

Solution 3 - node.js

Node.js, starting from version 8, provides a handy module to retrieve this kind of information.

async_hooks: an API to register callbacks tracking the lifetime of asynchronous resources created inside a Node.js application.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKFLView Question on Stackoverflow
Solution 1 - node.jsmscdexView Answer on Stackoverflow
Solution 2 - node.jsJacobView Answer on Stackoverflow
Solution 3 - node.jslsilvsView Answer on Stackoverflow