68

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?

KFL
  • 14,338
  • 12
  • 60
  • 80
  • 2
    Maybe this: http://stackoverflow.com/questions/13052548/node-js-how-to-attach-to-a-running-process-and-to-debug-the-server-with-a-conso can be useful to you? – Stefano Falsetto Sep 26 '14 at 11:21
  • @StefanoF No, I believe that's irrelevant. Thanks for commenting anyways. – KFL Oct 01 '15 at 00:14

3 Answers3

60

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.

mscdex
  • 93,083
  • 13
  • 170
  • 135
  • 5
    I would suggest to use an NPM module like [wtfnode](https://github.com/myndzi/wtfnode), [why-is-node-running](https://github.com/mafintosh/why-is-node-running) or [active-handles](https://www.npmjs.com/package/active-handles) to determine which piece of code is causing the issue. – cwouter Feb 25 '19 at 11:14
16

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();
Jacob
  • 72,750
  • 22
  • 137
  • 214
2

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.

lsilvs
  • 84
  • 3