94

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?

2
  • 3
    Maybe this: stackoverflow.com/questions/13052548/… can be useful to you? Commented Sep 26, 2014 at 11:21
  • 1
    @StefanoF No, I believe that's irrelevant. Thanks for commenting anyways. Commented Oct 1, 2015 at 0:14

3 Answers 3

82

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I would suggest to use an NPM module like wtfnode, why-is-node-running or active-handles to determine which piece of code is causing the issue.
But exercise due diligence: check the activity for each over on the npm registry: wtfnode, why-is-node-running, and active-handles. Of the three, only "why is node running" appears to still make sense in 2023.
I'm wondering why process._getActiveHandles() not return timerfd when I use setTimeout, I only see stdin, stdout, stderr and socket file descriptor in the returned array.
35

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();

1 Comment

This was fantastically easy and helpful!
4

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.