In this lesson, I introduce a memory leak into our node.js application and show you how to identify it using the Formidable nodejs-dashboard. Once identified, we will add garbage collection stats to the error console allowing us to correlate garbage collection with the increased memory usage.
Install:
npm i -D gc-profiler nodejs-dashboard
let express = require(‘express‘); let router = express.Router(); let faker = require(‘faker‘); let words = []; let profiler = require(‘gc-profiler‘); profiler.on(‘gc‘, (info) => { console.error(info); }); router.get(‘/‘, function(req, res, next) { let num = Math.floor(Math.random() * 1000) + 1; let searchterm = faker.lorem.words(num); let arr = searchterm.split(‘ ‘); arr.forEach(word => { words.push(word); // cause memory leak }); console.log(`Generating ${num} words`); res.send(searchterm); }); module.exports = router;
In the code, we can use ‘gc-profiler‘ to monitor the gb collection in order to see the memory leak in dashboard.
时间: 2024-10-24 23:54:14