I want my javascript to print a stack trace when I force close, so that I know where a function is hanging for instance. Is there a way to do this? I run the code with Node, specifically npx ts-node code.ts
. I imagine hijacking sigint might work, but then the console.trace would be from the sigint block and not the original code -- I am stuck making progress here.
Asked
Active
Viewed 500 times
-1

John Targaryen
- 1,109
- 1
- 13
- 29
-
1How are you executing said JavaScript? With Node? Or something else? – esqew Jul 23 '21 at 18:13
-
Yes, I've clarified that in the question :) – John Targaryen Jul 25 '21 at 22:04
-
does https://stackoverflow.com/questions/20165605/detecting-ctrlc-in-node-js help? – evolutionxbox Jul 25 '21 at 22:07
-
Could be a duplicate of https://stackoverflow.com/questions/24927233/nodejs-process-hang-how-could-i-debug-it-or-collect-dump and other similar – Wiktor Zychla Jul 25 '21 at 22:07
-
1Have you tried something like `npx --node-arg=-trace-sigint ts-node code.ts`? – esqew Jul 25 '21 at 23:38
-
@esqew I get `npx: the --node-arg argument has been removed.` – John Targaryen Jul 27 '21 at 03:03
-
@JohnTargaryen My apologies - forgot this feature was superseded by the near-equivalent `--node-options`. Have you tried something like *this*? `npx --node-options='-trace-sigint' ts-node code.ts`? – esqew Jul 27 '21 at 03:14
-
Yeah -- `--node-options='--trace-sigint'` works perfectly. Feel free to post an answer and claim the bounty (none of the other questions linked above have this solution; they are not duplicates). – John Targaryen Jul 27 '21 at 03:45
2 Answers
2
The Node runtime had the --trace-sigint
argument added in May 2020 (as part of nodejs/node#29207
for this very purpose.
When running through npx
, its --node-options
flag can be used to pass this option on to the runtime like so:
npx --node-options='--trace-sigint' ts-node code.ts

esqew
- 42,425
- 27
- 92
- 132
-
Turns out it only backtraces to a library function at `at processTicksAndRejections (node:internal/process/task_queues:96:5)`, and not to the actual function of the main code that calls the failed library function. Any ideas? – John Targaryen Aug 09 '21 at 00:22
0
Use the option --trace-sigint
.
The documentation states simply that this "Prints a stack trace on SIGINT."
Complete command:
npx --node-options='-trace-sigint' ts-node code.ts

Codebling
- 10,764
- 2
- 38
- 66