← 中文资源

简体中文版本

util.inspect 打印嵌套对象树

用 util.inspect 的 depth、compact、breakLength 选项打印嵌套对象:日志保持单行,深层结构既可读又不会在浅层深度下泄露细节。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

{
  id: 7,
  tags: [ 'cache', 'slow' ],
  meta: { attempts: 2, lastError: null },
  run: [Function: run]
}
{ id: 7, tags: [Array], meta: [Object], run: [Function: run] }
{ id: 7, tags: [ 'cache', 'slow' ], meta: { attempts: 2, lastError: null }, run: [Function: run] }
deep fields hidden at depth 0: true

实现说明

导入清单标出了平台接触面:inspect,全部来自 node:util。 演示用的数据放在这几个模块级绑定中:task。

使用要点

  • 唯一的导入 node:util 属于 Node.js 标准库。
  • 每一步打印都带着自己的标签:deep fields hidden at depth 0:。

常见问题

有第三方依赖吗?

不需要。导入解析到 Node.js 核心模块,运行时自带。

代码示例

import { inspect } from 'node:util';

const task = {
  id: 7,
  tags: ['cache', 'slow'],
  meta: { attempts: 2, lastError: null },
  run: () => 'noop',
};

console.log(inspect(task, { depth: 1 }));
console.log(inspect(task, { depth: 0, breakLength: Infinity }));

// compact single-line form for structured logs
console.log(inspect(task, { compact: true, breakLength: Infinity, depth: Infinity }));
console.log('deep fields hidden at depth 0:', !inspect(task, { depth: 0 }).includes('lastError'));