Node.js process graceful interruption from SIGINT. Interrupt the long async job only at certain safe interruption points. Force termination after receiving certain number of SIGINTs.
const gracefulSigint = require('./nodeGracefulSigint').gracefulSigint();
const doTaskAsync = require('./doTaskAsync');
async function doManyTasksAsync() {
const manyTaskInputs = new Array(1000);
for (const taskInput of manyTaskInputs) {
// Safe to terminate between the tasks.
if (gracefulSigint.shouldTerminate()) {
process.exit(-1);
return;
}
// Unsafe to terminate within the task.
await doTaskAsync(taskInput);
}
}
// Run the job only if the module is executed directly, not `require()`d.
if (!module.parent) {
// Enable graceful interruption.
gracefulSigint.setEnabled(true);
doManyTasksAsync().catch((error) => {
console.error(error);
});
}