Manage Memory and Garbage Collection in Node.js

Share this video with your friends

Send Tweet

In this lesson, you will learn how to use view and interpret the garbage collection activity of your node.js app via the console. You will also learn how to take heapdump snapshots and analyze them with Chrome Developer Tools to identify possible memory leaks. A sample app with a known memory leak is provided as part of the walk-through to illustrate how to use the tools in your own environments.

John
John
~ 8 years ago

I ran this lesson on Ubuntu 14.04, Node version 6.2.2. There was no memory leak activity reported.

output

john@john-aspire-7741:~/Documents/fenestra/development/gids-web/node-egghead/http$ node --trace_gc server-heapdump.js
[30883:0x28a71b0]       11 ms: Scavenge 2.1 (37.0) -> 2.0 (37.0) MB, 0.9 / 0 ms [allocation failure].
[30883:0x28a71b0]       16 ms: Scavenge 2.1 (37.0) -> 2.1 (38.0) MB, 1.0 / 0 ms [allocation failure].
[30883:0x28a71b0]      109 ms: Scavenge 4.0 (41.0) -> 3.7 (41.0) MB, 1.0 / 0 ms [allocation failure].
received request
received request
received request
received request

received request
received request
received request
received request
received request
received request
^C
john@john-aspire-7741:~/Documents/fenestra/development/gids-web/node-egghead/http$ node --version
v6.2.2

server-heapdump.js

const http = require('http')
const heapdump = require('heapdump')

function BigData() {
    var mem = Array(1000000).join("a")
}

const leak = []
const server = http.createServer((request, response) => {
    if (request.url === '/') {
        leak.push(new BigData())
        console.log('received request')
        response.writeHead(200, {"Content-Type" : "text/plain"})
        response.end('Hello world')
    }
})

server.listen(3000)
Will Button
Will Button(instructor)
~ 8 years ago

Yup. I was able to duplicate the results you show. The lesson is still accurate for versions of node 4.x and lower but I'll need to update it for v6. Thanks for pointing this out!

Vishwas Chouhan
Vishwas Chouhan
~ 8 years ago

I see you are requiring a module heap but it's not been referenced anywhere in the code. Where is the heap dump file created?

jpbamberg1993
jpbamberg1993
~ 7 years ago

Your log say "allocation on failure" mine says "allocation failure". Are they different?