Home > Back-end >  How can I produce a fatal error in Node.js?
How can I produce a fatal error in Node.js?

Time:07-22

I am trying to trigger the command line option console output

How to get a harmless fatal error in Node.js?

Already tried with sytnaxerror and reference error. But they are detected at runtime.

CodePudding user response:

One way to have NodeJS produce a fatal error is by running out of memory.

There's a V8 option to set the old memory section. Most variables in a running program are stored there.

node --max-old-space-size=1

On my machine anything under 5mb will make Node instantly crash (or rather after the first garbage collection), with a different error for 1-2mb, 3mb and 4mb. Simply running:

node --max-old-space-size=4 --report-on-fatalerror
ls -l report*

Will generate a report.[date].json file.

Relying on a magic number like "4" is iffy and perhaps you want to control when it crashes. You can just set the value low enough to not crash instantly and then allocate enough memory to trigger a garbage collector that hits the limit, eg:

# Enough memory to not instantly crash
# -e evaluates a script that allocates some memory.
# It logs every loop iteration.
node --max-old-space-size=10 --report-on-fatalerror -e 'a=[];for(i=0;i<1024**2;i  )console.log(i),a.push(String(i).repeat(10000))'

ls -l report*
  • Related