32. 在 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:
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中文官方 http://nodejs.cn/

更多知识点 请关注:笔墨是小舟

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。