使用Chrome+node-inspector查找NodeJS內存泄漏

關鍵字: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.htmlapp

運行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應用的內存泄露。下面是其中的一些:

  • https://github.com/lloyd/node-memwatch。注:若是」node install memwatch「安裝失敗,那就試試」node install memwatch-next「
  • Jimb Esser的node-mtrace,它使用了GCC的mtrace工具來分析堆的使用。
  • Dave Pacheco的node-heap-dump對V8的堆抓取了一張快照並把全部的東西序列化進一個巨大的JSON文件。它還包含了一些分析研究快照結果的JavaScript工具。
  • Danny Coates的v8-profilernode-inspector提供了綁定在Node中的V8分析器和一個基於WebKit Web Inspector的debug界面。

 

更多內容請參考:

Memory leak patterns in JavaScript。

The node.js Profiling Guide that Hasn’t Existed - Finding The Cause of a Memory Leak Using Heap Snapshots。

相關文章
相關標籤/搜索