Skip to content

Instantly share code, notes, and snippets.

@JasonGiedymin
Last active May 27, 2022 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JasonGiedymin/6f26a6c5aa42f852142bca92715b9271 to your computer and use it in GitHub Desktop.
Save JasonGiedymin/6f26a6c5aa42f852142bca92715b9271 to your computer and use it in GitHub Desktop.
Bash trap a nodejs application - useful for docker
#!/usr/bin/env bash
set -e
sig_handler() {
exit_status=$? # Eg 130 for SIGINT, 128 + (2 == SIGINT)
if [[ exit_status -gt 0 ]]; then
cat <<EOF
!!!
WARN: signal [$exit_status] recieved by entrypoint ... returning it"
!!!
EOF
else
echo "INFO: signal [$exit_status] recieved by entrypoint ... returning it"
fi;
exit "$exit_status"
}
trap sig_handler INT HUP TERM QUIT EXIT KILL
run() {
echo "INFO: entrypoint running app.js with params ..."
node ./test.js $@
}
run $@
const SLOW_START_DELAY=500;
const WAIT_TIME = 5000;
function start(choice) {
// simulate "slow start"
setTimeout(complete, WAIT_TIME, choice);
console.log(`INFO: Running nodejs app with simulated choice ${choice} in ${WAIT_TIME}ms ...`);
console.log(`Legend:\n--------------\n 0-10: no error \n 11-50: exception\n 51-75: error obj\n 76-100: self sigkill`)
}
function complete(choice) {
// 0-10 no error
// 11-50 exception
// 51-75 error obj
// 76-100 self sigkill
if (choice >= 11 && choice <= 50) {
throw "SIMULATED EXCEPTION :-D";
} else if (choice >= 51 && choice <= 75) {
throw new Error("SIMULATED ERROR OBJ :-D");
} else if (choice >= 76 && choice <= 100) {
process.kill(process.pid, 'SIGKILL');
} else {
console.log("INFO: app complete, exiting cleanly.");
process.exit();
}
}
function main() {
var args = process.argv.slice(2);
if ( args[0] != null ) {
setTimeout(start, SLOW_START_DELAY, args[0])
} else {
var choice = Math.floor(Math.random() * 100);
setTimeout(start, SLOW_START_DELAY, choice);
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment