65

This is different to other questions regarding an error message in Node that reads RangeError: Maximum call stack size exceeded in that I know exactly why I'm getting this error message. It's happening because I'm recursing, recursing quite a lot in fact.

Thanks.

Yves M.
  • 29,855
  • 23
  • 108
  • 144
thomas-peter
  • 7,738
  • 6
  • 43
  • 58

2 Answers2

92

From node --help:

node --max-stack-size=val

Update: as the comments indicate, even though the help text still lists the --max-stack-size option, in node v0.10.x you need to use --stack-size instead.

node --stack-size=val
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • pretty obvious now i'm looking at --help :) – thomas-peter Jul 04 '12 at 16:08
  • 5
    For some reason, I find --stack-size work for me, not --max-stack-size. – boh May 17 '13 at 07:01
  • 1
    What would be the maximum safe stack size? Would that depend on CPU cycles? – Logan Oct 18 '13 at 03:50
  • Logan, I believe this is an issue of memory. – astone26 Feb 24 '14 at 09:54
  • node --stack-size=8192 is the max value on my Ubuntu Server. Anything more than that doesn't increase the max recursion of my functions. Note that the unit of --stack-size is KB, so that's about 8 MB. In Windows I can't get more than 1 MB. – cprcrack Oct 08 '14 at 11:25
  • 4
    having the same issue, if increase the stack size , new error come - segmentation fault – NeiL May 27 '15 at 05:41
  • "segmentation fault" here as well – phani Nov 02 '15 at 02:48
  • 2
    »It seems to be a common misunderstanding but --stack_size=... doesn't change the size of the stack, it tells node/V8 how big it is. If you set it to a value that's bigger than the actual size, it runs over.« - https://github.com/nodejs/node/issues/17416#issuecomment-348545847 – Björn Höhrmann Jul 02 '18 at 01:01
29

In node version 5 and 6, I have verified that the option to set maximum stack size is "--stack_size" (with an underscore):

$  node --v8-options
[...]
--stack_size (default size of stack region v8 is allowed to use (in kBytes))
      type: int  default: 984

To increase the maximum stack size, just issue something like:

$ node --stack_size=1200

As noted by others, be aware that increasing this value may lead to a segmentation fault. The maximum safe value for me with version 6 is 1361, but seems higher with version 5.

Looking at the bigger picture, increasing stack size may not solve all your issues. When writing recursive functions in node, your best strategy is to write them in a tail-recursive manner, since version 6 supports proper tail calls. This will eliminate stack size overflows.

Update: the comment about tail calls doesn't apply to Node.js anymore. They've removed tail-call optimization from the engine in version 8. See this answer for some more info.

shkaper
  • 4,689
  • 1
  • 22
  • 35
Florent Angly
  • 495
  • 5
  • 8