You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在VS Code终端中如何完整打印Node.js的嵌套对象?

Node.js终端完整打印嵌套对象的解决方法

在VS Code终端用Node.js开发时,用console.log()打印多层嵌套对象,深层结构会被截断显示为[Object],没法看到完整内容。

比如执行这段代码:

const object = { data: 1, next: { data: 2, next: { data: 3, next: { data: 4, next: null }}}}; 
console.log(object);

终端默认输出是:

>>> { data: 1, next: { data: 2, next: { data: 3, next: [Object] } } }

想要完整显示整个嵌套对象,有以下几种方法:

方法一:使用console.dir()指定深度

console.dir()支持配置打印深度,设置depth: null就能递归显示所有层级的对象:

console.dir(object, { depth: null });

输出结果:

>>> { data: 1, next: { data: 2, next: { data: 3, next: { data: 4, next: null }}}}

方法二:用JSON.stringify()转为字符串

把对象转成JSON字符串,既能完整显示结构,还能通过参数格式化输出:

// 不带缩进的紧凑输出
console.log(JSON.stringify(object));
// 带2空格缩进的格式化输出
console.log(JSON.stringify(object, null, 2));

对应的输出分别是:

>>> {"data":1,"next":{"data":2,"next":{"data":3,"next":{"data":4,"next":null}}}}

和

>>> {
  "data": 1,
  "next": {
    "data": 2,
    "next": {
      "data": 3,
      "next": {
        "data": 4,
        "next": null
      }
    }
  }
}

方法三:全局修改Node.js的打印深度配置

如果需要多次打印嵌套对象,不想每次都加参数,可以修改util.inspect的默认配置,让console.log()默认显示所有层级:

const util = require('util');
util.inspect.defaultOptions.depth = null;

console.log(object); // 现在会完整显示整个对象

内容的提问来源于stack exchange,提问作者Zohan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 04:25:02