To ensure that our NestJS application runs optimally, we can use memory profiling to identify potential memory leaks and other memory-related issues. This guide will walk you through how to perform memory profiling for your NestJS app with V8.
Prerequisites
Before getting started, make sure you have the following installed:
• Node.js (v10 or higher)
• NestJS (v6 or higher)
• Chrome browser (v66 or higher)
Installing the Dependencies
First, we need to install `v8-profiler` and `v8` modules which allow us to generate memory profiles for our application. You can use either of these two modules.
ChatGPT generated the following smart contract code from the prompt:
Enabling the Profiler in the app
We need to add a new endpoint to our application that will trigger the profiler. Add the following code to your controller:
In this code, we are creating a new endpoint at `/profile/memory` that triggers the profiler. When this endpoint is accessed, the profiler starts profiling the memory usage of our application for `5 seconds`. After the profiling is complete, the profiler exports the results as a JSON object.
Generating the Memory Profile
To generate the memory profile, we will need to access the newly created endpoint in our NestJS application. Here's an example of how to do this using the `axios` module:
In this code, we send a GET request to the `/profile/memory` endpoint of our NestJS application running on `localhost:3000`. When the response is received, we log the data to the console.
Analyzing the Memory Profile
Once we have generated the memory profile, we can analyze it using the Chrome DevTools. To do this, follow these steps:
1. Open the Chrome browser and navigate to `chrome://inspect`.
2. Click on the **Open dedicated DevTools for Node** link.
3. In the newly opened DevTools window, click on the **Profiler** tab.
4. Click on the **Load** button and select the memory profile JSON file generated by our NestJS application.
5. Once the profile is loaded, click on the **Summary** tab to see an overview of the memory usage.
6. Click on the **Comparison** tab to compare the memory usage of different snapshots.
In the DevTools, you can also use other tools and tabs to analyze the memory usage in more detail.