Skip to content

Instantly share code, notes, and snippets.

@Raynos Raynos/ Secret
Created Jun 23, 2014

What would you like to do?

What keeps my process open

Sometimes when you run your process (or test script) with node, the process won't exit cleanly.

My process won't exit cleanly, help what do I do.

If your process won't exit cleanly it means something is keeping the event loop open.


  • setTimeout or setInterval
  • open file descriptors (fs, net, http, etc.)
  • open database connections (redis, etc.)

Debugging an event loop

Node has a build in primitive called process._getActiveHandles() that allows you to inspect which handles are currently keeping your process open.

var setInterval = require('timers').setInterval;

setInterval(function () {
  var handles = process._getActiveHandles();

  console.log('no of handles', handles.length);
  handles.forEach(function (obj) {
    if ('ontimeout' in obj) {
      console.log('timer handle', obj);
    } else if ('readable' in obj && 'writable' in obj) {
      // to debug stream handles print the _events functions
      // to string and figure out what kind of stream they are
      // then stare really hard at the source code
      // console.log(obj._events.end.toString());
      console.log('stream handle', obj);
    } else {
      console.log('unknown handle', obj);
}, 5000).unref();

Here we poll the handles every 5 seconds and print them.

See this open handles gist for more discussion.

Identifying what type of tcp socket it is.

There are two tricks for figuring out what a tcp socket is.

One is to look at socket._events[name].toString() and either recognise the source code of the event handler or github search for it.

I once searched for a function and found it in the node-redis source code and thus knew that socket was a redis connection.

The other trick is to take a look at the _readableState and peek at the buffer in the stream, if your lucky you can identify what kind of HTTP request it was from the body.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.