process.memoryUsage()


返回一个对象,描述以字节为单位测量的 Node.js 进程的内存使用情况。

【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
// }
  • heapTotalheapUsed 指的是 V8 的内存使用情况。
  • external 指的是与 V8 管理的 JavaScript 对象绑定的 C++ 对象的内存使用情况。
  • rss(常驻内存集大小)是进程在主内存设备中占用的空间量(这是已分配内存总量的一个子集),包括所有的 C++ 和 JavaScript 对象及代码。
  • arrayBuffers 指为 ArrayBufferSharedArrayBuffer 分配的内存,包括所有 Node.js Buffers。这也包含在 external 值中。当 Node.js 作为嵌入式库使用时,该值可能为 0,因为此情况下可能不会跟踪 ArrayBuffer 的分配。

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

【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.】

process.memoryUsage() 方法会遍历每个页面以收集内存使用信息,这可能会因为程序的内存分配而导致速度较慢。

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