NodeJS v8 getheapstatistics method| How to find heap size?

In this tutorial, You learn the getHeapStatistics method in the v8 module of nodejs with examples

This includes how to find below things from the javascript code

  • How to get the value of max_old_space_size from the code?
  • get the max heap size of a nodejs application
  • Retrieve heap memory for string objects
  • total_available_size
  • max-old-space-size

V8 is an engine is used internally by the Nodejs environment. You can check v8 version and 32 bit or 64 bit for Nodejs

Sometimes, To debug node out of memory errors, We need to know the heapsize of an environment and application. To get the all above information, Nodejs has an inbuilt module v8, It has an inbuilt getHeapStatistics to get statistical information about the heap memory of an application running in the entire system.

V8 has another method [getHeapSpaceStatistics](/nodejs-v8-getheapspacestatistics-method) about statistics of spaces in the system.

Syntax:

getHeapStatistics();

It returns an object of the following properties

  • total_heap_size :Allocated total heap size in bytes, It increases if used_heap_size configured
  • total_heap_size_executable : heap size in bytes allocated for compilation of byte code
  • total_physical_size : total available size of an harddisk
  • total_available_size : total available heap size
  • heap_size_limit: Limit on heap size default is max_old_space_size value
  • used_heap_size: heap size in bytes allocated to the application
  • malloced_memory: Current mallocated memory
  • peak_malloced_memory: peak allocated memory
  • does_zap_garbage : set to 0 or 1 to indicate zap_code_space option is enabled or not
  • number_of_native_contexts : active top-level native contexts
  • number_of_detached_contexts : detached context which is not garbage collected

This will give a useful heap of information

v8 getHeapStatistics method example

first import the v8 module using the require keyword in the ES5 syntax

const v8 = require('v8');

Here is a code for v8 getHeapStatistics example
info.js
```javascript
const v8module = require('v8');

console.log(v8module.getHeapStatistics());

running info.js in the command line with the node command

node info.js

It outputs an object

{
  "total_heap_size": 4468736,
  "total_heap_size_executable": 524288,
  "total_physical_size": 4468736,
  "total_available_size": 4342053000,
  "used_heap_size": 2851944,
  "heap_size_limit": 4345298944,
  "malloced_memory": 8192,
  "peak_malloced_memory": 123168,
  "does_zap_garbage": 0,
  "number_of_native_contexts": 1,
  "number_of_detached_contexts": 0
}

Conclusion

You learned the getHeapStatistics method in the v8 module of the nodejs application. This gives heap statistics information of a nodejs application as well as the entire environment.