process.memoryUsage()


返回描述 Node.js 进程的内存使用量(以字节为单位)的对象。

import { memoryUsage } from 'node:process';

console.log(memoryUsage());
// 打印:
// {
//  rss: 4935680,
//  heapTotal: 1826816,
//  heapUsed: 650472,
//  external: 49879,
//  arrayBuffers: 9386
// }const { memoryUsage } = require('node:process');

console.log(memoryUsage());
// 打印:
// {
//  rss: 4935680,
//  heapTotal: 1826816,
//  heapUsed: 650472,
//  external: 49879,
//  arrayBuffers: 9386
// }
  • heapTotalheapUsed 指的是 V8 的内存使用量。
  • external 指的是绑定到 V8 管理的 JavaScript 对象的 C++ 对象的内存使用量。
  • rss,常驻集大小,是进程在主内存设备(即总分配内存的子集)中占用的空间量,包括所有 C++ 和 JavaScript 对象和代码。
  • arrayBuffers 是指为 ArrayBufferSharedArrayBuffer 分配的内存,包括所有 Node.js Buffer。 这也包含在 external 值中。 当 Node.js 被用作嵌入式库时,此值可能为 0,因为在这种情况下可能不会跟踪 ArrayBuffer 的分配。

当使用 Worker 线程时,则 rss 将是对整个进程都有效的值,而其他字段仅涉及当前线程。

process.memoryUsage() 方法遍历每个页面以收集有关内存使用情况的信息,这可能会根据程序内存分配而变慢。

Returns an object describing the memory usage of the Node.js process measured in bytes.

import { memoryUsage } from 'node:process';

console.log(memoryUsage());
// Prints:
// {
//  rss: 4935680,
//  heapTotal: 1826816,
//  heapUsed: 650472,
//  external: 49879,
//  arrayBuffers: 9386
// }const { memoryUsage } = require('node:process');

console.log(memoryUsage());
// Prints:
// {
//  rss: 4935680,
//  heapTotal: 1826816,
//  heapUsed: 650472,
//  external: 49879,
//  arrayBuffers: 9386
// }
  • heapTotal and heapUsed refer to V8's memory usage.
  • external refers to the memory usage of C++ objects bound to JavaScript objects managed by V8.
  • rss, Resident Set Size, is the amount of space occupied in the main memory device (that is a subset of the total allocated memory) for the process, including all C++ and JavaScript objects and code.
  • arrayBuffers refers to memory allocated for ArrayBuffers and SharedArrayBuffers, including all Node.js Buffers. This is also included in the external value. When Node.js is used as an embedded library, this value may be 0 because allocations for ArrayBuffers may not be tracked in that case.

When using Worker threads, rss will be a value that is valid for the entire process, while the other fields will only refer to the current thread.

The process.memoryUsage() method iterates over each page to gather information about memory usage which might be slow depending on the program memory allocations.