Create a V8 Heap Snapshot in ElectronJS

23 Jun, 2020
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.
NodeJS is a JavaScript runtime which uses the Chrome’s V8 engine. NodeJS has many advantages which make it quite popular for the first choice for backend solutions including RESTful APIs. However, NodeJS does have some drawbacks associated with it. One of the major disadvantages of NodeJS is Performance bottlenecks due to heavy computation tasks. This is because NodeJS is single-threaded. This results in slow processing which is why NodeJS is not recommended for heavy computation. In an Electron application, we need to ensure that NodeJS does not have a memory leak which will further slow down the performance. Hence, Electron provides us with a way by which we can take V8 Heap Snapshots using the instance methods of the BrowserWindow Object and the webContents property. We can then use this heap to find Memory leaks in our Electron application using the Chrome DevTools. This tutorial will demonstrate how to take V8 Heap Snapshots and upload it to Chrome DevTools for further Inspection in an Electron application. 
We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.
Project Structure:  
Example: Follow the Steps given in Drag and Drop Files in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to setup the Electron application remain the same. 
package.json: 
{
  "name": "electron-snapshot",
  "version": "1.0.0",
  "description": "Snapshot of Electron",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "keywords": [
    "electron"
  ],
  "author": "Radhesh Khanna",
  "license": "ISC",
  "dependencies": {
    "electron": "^8.3.0"
  }
}

Create the assets folder according to the project structure. We will be using the assets folder as the default path to store the V8 Heap Snapshot file generated by the application. The file extension for a V8 Heap Snapshot file is .heapsnapshot. Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following result. 
Heap Snapshots in Electron: The BrowserWindow Instance and webContents Property are part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module. 
index.html: Add the following snippet in that file. The Create V8 Heap Snapshot button does not have any functionality associated with it yet.
html
<h3>  Create a Snapshot in Electron</h3><button id="snap">  Create V8 Heap Snapshot</button>
index.js: Add the following snippet in that file.
javascript
const electron = require('electron')const path = require('path')  // Importing BrowserWindow using Electron remoteconst BrowserWindow = electron.remote.BrowserWindow;  let win = BrowserWindow.getFocusedWindow();  // let win = BrowserWindow.getAllWindows()[0];const filepath = path.join(__dirname, '../assets/snap.heapsnapshot')  var snap = document.getElementById('snap');snap.addEventListener('click', (event) => {    win.webContents.takeHeapSnapshot(filepath)        .then(console.log('V8 HeapSnapshot taken Successfully'))        .catch(err => {            console.log(err);        });});
 The win.webContents.takeHeapSnapshot(file path) Instance method simply takes a V8 Heap Snapshot of the application memory and Saves it to the given file path. This Instance method returns a Promise and it is resolved when the snapshot file has been created successfully at the given file path. It takes in the following parameters.
filepath: String This parameter cannot be Empty. It specifies the filepath where we would like to save the generated Heap Snapshot file. In our code, we have saved the generated Heap Snapshot file to the assets folder along with the name of the file using the path module.
To get the current BrowserWindow Instance in the Renderer Process, we can use some of the Static Methods provided by the BrowserWindow object. 
BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly refered from the Array as shown in the code.
BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred using this method as shown in the code.
Output: Upon launching the application, we should see the following result. 
snap.heapsnapshot: 
The snap.heapsnapshot file is just a random set of numbers. To make any sense of this file, we need to upload it to the Chrome DevTools so that we can evaluate it for Memory Leaks. Follow the given Steps to upload this file to Chrome Devtools. 
Step 1: Within the Electron Application, launch Chrome DevTools incase they have been disabled at application Startup. We can launch using the Keyboard Shortcut, Ctrl+Shift+I. In our code, we have enabled them by default on application startup using the win.webContents.openDevTools() Instance method of the webContents property specified in the main.js file.
Step 2: Within the DevTools, go to the Memory Tab and within Select profiling type, choose the Heap snapshot option. After that, Click on the Load Button. This should open a native File System dialog.
Step 3: Navigate to where we have stored the .heapsnapshot file and click on Open. This will upload the file and we can now view it within the Chrome DevTools. Click on the file to see the Statistics for the application.
Output:Note: We can also use the process.takeHeapSnapshot(filePath) method of the process object to create a V8 Heap Snapshot file of the Electron application. The process object in Electron is an extension of the NodeJS process object which provides an additional variety of Instance method and properties which can be used in the Electron application. 
ElectronJS
HTML
JavaScript
Node.js
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.