Tomáš Zato
Tomáš Zato

Reputation: 53119

How to figure out what's holding Node.js from exiting?

I have this problem very often with various Node.js scripts that I write. After everything is done, they do not exit. Usually, it's an unclosed socket or readline interface.

When the script gets bigger, this is really hard to find out. Is there a tool of some sort that would tell me what's NodeJS waiting for? I'm asking for a generic solution that would help debug all cases of NodeJS not exiting when it's supposed to.

Samples:

Exhibit I. - Process stdin blocks node even after listener is removed

const readline = require('readline');
readline.emitKeypressEvents(process.stdin);
if (typeof process.stdin.setRawMode == "function")
    process.stdin.setRawMode(true);


const keypressListener = (stream, key) => {
    console.log(key);
    process.stdin.removeListener("keypress", keypressListener);
}
process.stdout.write("Press any key...");
process.stdin.on("keypress", keypressListener);

Exhibit II. - readline blocks Node if you forget to close the interface

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

Exhibit III. - Forgotten setInterval will also block node, good luck finding it

setInterval(() => { }, 2000);

Upvotes: 5

Views: 1881

Answers (1)

Evert
Evert

Reputation: 99525

Would why-is-node-running work? Seems to do exactly what you need.

Upvotes: 5

Related Questions