關鍵字: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應用的內存泄露。下面是其中的一些:
更多內容請參考: