Node.js 教程

在 Node.js 中如何记录对象

2020-12-04 16:44:17 更新   浏览量: 205
上一章:Node.js 中的错误处理 本章完

学习其他章节 nodejs入门教程 nodejs实战

在 Node.js 中如何记录对象

When you type console.log() into a javascript program that runs in the browser, that is going to create a nice entry in the Browser Console:


Once you click the arrow, the log is expanded, and you can clearly see the object properties:


In Node.js, the same happens.

We don’t have such luxury when we log something to the console, because that’s going to output the object to the shell if you run the Node.js program manually, or to the log file. You get a string representation of the object.

Now, all is fine until a certain level of nesting. After two levels of nesting, Node.js gives up and prints [Object] as a placeholder:

const obj = {
  name: 'joe',
  age: 35,
  person1: {
    name: 'Tony',
    age: 50,
    person2: {
      name: 'Albert',
      age: 21,
      person3: {
        name: 'Peter',
        age: 23
      }
    }
  }
}
console.log(obj)


{
  name: 'joe',
  age: 35,
  person1: {
    name: 'Tony',
    age: 50,
    person2: {
      name: 'Albert',
      age: 21,
      person3: [Object]
    }
  }
}

How can you print the whole object?

The best way to do so, while preserving the pretty print, is to use

console.log(JSON.stringify(obj, null, 2))

where 2 is the number of spaces to use for indentation.

Another option is to use

require('util').inspect.defaultOptions.depth = null
console.log(obj)

but the problem is that the nested objects after level 2 are now flattened, and this might be a problem with complex objects.

扫二微码
上一章:Node.js 中的错误处理 本章完
学习其他章节 nodejs入门教程 nodejs实战

最近更新 免责声明 关于我们

Copyright © 2004-2021 前端教程 qianduan.cn All Rights Reserved   陕ICP备2021014585号-1 陕公网安备 61012402000223号 前端教程

友情链接:  前端工具 前端插件 前端小川

Node.js 教程