Ubuntu下如何查看Node.js堆内存限制?解决堆内存溢出报错
Hey there! Sorry to hear you're stuck with that heap out of memory error—let's break down how to check your Node.js heap memory limits on Ubuntu, step by step.
1. Check Heap Memory Usage & Limits for a Running Node Process
If you want to see the current heap stats for an active Node.js process, you can use Node's built-in APIs directly:
Open the Node REPL by running:
nodeOnce in the REPL, run this to get a quick overview of memory usage:
console.log(process.memoryUsage());This will output an object with key values like:
heapUsed: Amount of heap memory currently in use (in bytes)heapTotal: Total heap memory allocated to the process (in bytes)external: Memory used by C++ objects bound to JavaScript objects
For more detailed heap limits, use the
v8module (built into Node.js):const v8 = require('v8'); console.log(v8.getHeapStatistics());Look for the
heap_size_limitfield—this is the maximum heap memory the process can use (in bytes).
2. Check Node.js Default Heap Memory Limit
To find out the default maximum heap size that Node.js uses (before any custom flags), run this command in your Ubuntu terminal:
node --v8-options | grep -i "max_old_space_size"
This will return something like:
--max-old-space-size (size in MB) Default: 1400
The max_old_space_size is the main component of Node's heap memory limit—this is the maximum amount of memory allocated to the "old generation" (long-lived objects) in the V8 engine. On 32-bit systems, the default is typically around 700MB instead.
Quick Tip to Fix the OOM Error
If you need to increase the heap limit for your script, you can launch Node with the --max-old-space-size flag, specifying the limit in MB:
node --max-old-space-size=2048 your-app.js
This sets the heap limit to 2GB—adjust the number based on your system's available memory.
内容的提问来源于stack exchange,提问作者Shivendra Kadam

