如何监控Node.js的内存使用情况?

时间:2013-11-16 12:43:12

标签: javascript node.js memory

如何监控Node.js的内存使用情况?

7 个答案:

答案 0 :(得分:119)

内置的process模块有一个方法memoryUsage,可以深入了解当前Node.js进程的内存使用情况。以下是64位系统上Node v0.12.2中的示例:

$ node --expose-gc
> process.memoryUsage();  // Initial usage
{ rss: 19853312, heapTotal: 9751808, heapUsed: 4535648 }
> gc();                   // Force a GC for the baseline.
undefined
> process.memoryUsage();  // Baseline memory usage.
{ rss: 22269952, heapTotal: 11803648, heapUsed: 4530208 }
> var a = new Array(1e7); // Allocate memory for 10m items in an array
undefined
> process.memoryUsage();  // Memory after allocating so many items
{ rss: 102535168, heapTotal: 91823104, heapUsed: 85246576 }
> a = null;               // Allow the array to be garbage-collected
null
> gc();                   // Force GC (requires node --expose-gc)
undefined
> process.memoryUsage();  // Memory usage after GC
{ rss: 23293952, heapTotal: 11803648, heapUsed: 4528072 }
> process.memoryUsage();  // Memory usage after idling
{ rss: 23293952, heapTotal: 11803648, heapUsed: 4753376 }

在这个简单的示例中,您可以看到为10M元素消费者分配大约80MB的数组(请查看heapUsed)。 如果您查看V8的源代码(Array::NewHeap::AllocateRawFixedArrayFixedArray::SizeFor),那么您将看到数组使用的内存是固定值加上长度乘以大小一个指针。后者在64位系统上是8个字节,这证实观察到的8 x 10 = 80MB的内存差异是有道理的。

答案 1 :(得分:58)

node-memwatch:检测并查找Node.JS代码中的内存泄漏。 查看本教程Tracking Down Memory Leaks in Node.js

答案 2 :(得分:36)

另外,如果您想了解全局内存而不是节点进程':

var os = require('os');

os.freemem();
os.totalmem();

See documentation

答案 3 :(得分:26)

原来memwatch基本上已经死了。请尝试使用memwatch-next,这似乎在现代版本的Node上运行良好。

答案 4 :(得分:3)

在Linux / Unix上(注意:Mac OS是Unix)使用top并按M( Shift + M )按内存使用情况对进程进行排序

在Windows上使用任务管理器。

答案 5 :(得分:1)

您可以使用node.js memoryUsage

const formatMemmoryUsage = (data: any) => `${Math.round(data / 1024 / 1024 * 100) / 100} MB`

const memoryData = process.memoryUsage()

const memmoryUsage: {
            rss: `${formatMemmoryUsage(memoryData.rss)} -> Resident Set Size - total memory allocated for the process execution`,
            heapTotal: `${formatMemmoryUsage(memoryData.heapTotal)} -> total size of the allocated heap`,
            heapUsed: `${formatMemmoryUsage(memoryData.heapUsed)} -> actual memory used during the execution`,
            external: `${formatMemmoryUsage(memoryData.external)} -> V8 external memory`,
        }

console.log(memoryUsage)
/*
{
    "rss": "177.54 MB -> Resident Set Size - total memory allocated for the process execution",
    "heapTotal": "102.3 MB -> total size of the allocated heap",
    "heapUsed": "94.3 MB -> actual memory used during the execution",
    "external": "3.03 MB -> V8 external memory"
}
*/

答案 6 :(得分:0)

如果您使用 express.js 框架,那么您可以使用 express-status-monitor。它非常易于集成,并以图形格式提供 CPU 使用率、内存使用率、响应时间等信息。

enter image description here