SIGINT, beforeExit and exit event handlers not called for ctrl-c keypress when application output is piped on

1.4k Views Asked by At

Note: I've already seen SIGINT handler in NodeJS app not called for ctrl-C (Mac) but it seems it's not my case.

I have a Node.js application - a Discord bot that uses Pino for logging. Main file, app.js is like this:

...
const logger = pino();
const client = new Discord.Client();

process
    .on('SIGINT', () => {
        console.log('SIGINT');

        client.destroy();
        logger.info('Exiting');
    })
    .on('beforeExit', () => { console.log('beforeExit'); }
    .on('exit', () => { console.log('exit'); }

client.on('ready', () => {
    logger.info(`Logged in`);
});

client.login(process.env.TOKEN);

when I start it just with node ./dist/app.js and press ctrl-c, it works - I get "SIGINT" from console.log(), "Exiting" from logger and "beforeExit", "exit" from console again. But I want to use a run script to redirect logging output to various files and to console:

#!/bin/bash
node ./dist/app.js | \
tee -a \
  ./logs/complete.log \
  >(jq -cM --unbuffered 'select(.level == 40)' >> ./logs/user.log) \
  >(jq -cM --unbuffered 'select(.level >= 50)' >> ./logs/error.log)  | \
./node_modules/.bin/pino-pretty --levelFirst --ignore hostname,pid,ctx --translateTime SYS:standard

But now when I press ctrl-c it just exits silently, "SIGINT" handler is not activated at all. Same for "beforeExit" and "exit". It seems that ctrl-c is intercepted somewhere down the pipe.

So, how to make the mentioned handlers work? Also, could anyone offer an explanation why this happens and - if it's really something with the pipe - how breaking a pipe works in regard to initiating process?

0

There are 0 best solutions below