Exit Node.js process after event loop is empty OR after timeout
<p>I have a Node app doing some asynchronous things, and I can't take the chance that one of the many modules does something bad and gets stuck, so the app will never exit. (It just happened when sending log messages to a service.)</p>

<p>I can't use <code>process.exit</code> directly, because it will terminate no matter how many asynchronous operations are pending. Still I'd like to exit as early as possible, so this won't do:</p>

<pre><code>function exit() {
    setTimeout(function() {
        process.exit(1);
    }, 10000);
}
</code></pre>

<p>Because that will wait 10 seconds, even if everything went ok and all async events finished after 1 second.</p>

<p>I'm considering checking if the event loop is empty except for this timer, then exit. That could possibly be done through some <a href="https://stackoverflow.com/a/32617487/70894">undocumented process methods</a>, but I prefer avoiding shady stuff like that. Any ideas about a better way to solve this?</p>