Capturing Ctrl+C (SIGTERM) in a subcommand
gvensan opened this issue · comments
Hello, This may have been discussed before - I could not find a way for this.
I am not using executable for the subcommand, hence cannot use exitHandler where I can catch the signals at process level. In a classic use of commander, subcommand execution - is there anyway to capture the SIGTERM in order to do some housekeeping work. An example would be of great help.
If this is already answered/resolved, my apologies - please point me to a sample.
Not sure about your subcommand setup. Are you using subcommands with action handlers?
Yes, have action handlers. sorry, If I was not clear.
Ok, so the action handlers are just running javascript callbacks. Node supports listening for signals. So nothing Commander specific, just the normal signal handling?
const { Command } = require('commander');
const process = require('node:process');
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
const program = new Command();
program.command('sleep')
.action(async () => {
await sleep(5000);
});
process.on('SIGINT', () => {
console.log('Received SIGINT.');
// Should we exit here?
});
console.log('Before parse');
program.parseAsync().then(() => {
console.log('After parse');
});
% node index.js sleep
Before parse
After parse
% node index.js sleep
Before parse
^CReceived SIGINT.
After parse
Thank you very much. The snippet helped!
I was running on a older version of commander (npm) and had the experimental warning suppressed as recommended by
nodejs/node#30810 (comment)
const { emit: originalEmit } = process;
process.emit = (event, error) => event === 'warning' && error.name === 'ExperimentalWarning' ? false : originalEmit.apply(process, arguments);
I realize now, this is not required as I had upgraded to latest commander version. This was preventing the signal handling.
Again, thanks a lot for a quick turn around. Much appreciated!
BTW, Love commander - well structured, friendly and covers all my scenarios.
(Thanks for update.)