关键字:NodeJS, 内存泄漏,node-inspector,Chromehtml
OS:Windows 10node
本文介绍如何使用node-inspector+Chrome查找nodejs内存泄漏。git
1.建立一个Express app, 参考http://www.cnblogs.com/ldlchina/p/4054974.html。github
修改app.js内容以下:web
//app.js var app = require('express')(); var http = require('http').Server(app); var leakobjs = []; function LeakClass(){ this.x = 1; } app.get('/', function(req, res){ console.log('get /'); for(var i = 0; i < 1000; i++){ leakobjs.push(new LeakClass()); } res.send('<h1>Hello world</h1>'); }); http.listen(3000, function(){ console.log('listening on port 3000'); });
运行cmd:”node app.js“express
在Chrome里面打开页面:http://localhost:3000/。不停的刷新给页面,nodejs的内存将不停的增加。数组
2.安装使用node-inspector来调试后台程序。请参考http://www.cnblogs.com/ldlchina/p/3551277.html。app
运行cmd: "node --debug app.js"。ide
运行cmd: "node-inspector"。工具
3.在Chrome里面打开http://127.0.0.1:8080/debug?port=5858, 以下图:
4.选择”Profiles“标签,选择”Take Heap Snapshot“,点击”Take Snapshot“。以下图
5.打开一个新的Chrome页面,运行http://localhost:3000/。
6.再次选择”Profiles“标签,选择”Take Heap Snapshot“,点击”Take Snapshot“。
选择Comparison,你将看到”LeakClass“致使了内存的增加,以下图。这样咱们能够检查代码中关于LeakClass的部分,经验告诉咱们要避免不限制的增加数组,不然在大访问量的状况下内存会耗光。
如今已经有许多好用且不断加强的工具用于定位Node.js应用的内存泄露。下面是其中的一些:
更多内容请参考: