How to record objects in Node

Record objects in Node.js

When you typeconsole.log()Enter the JavaScript program running in the browser, which will create a nice entry in the browser console:

After clicking the arrow, the log will be expanded and you can clearly see the object properties:

In Node, the same happens.

When we log something to the console, we don't have that luxury, because if you run the Node program manually or output it to a log file, this will output the object to the shell. You will get a string representation of the object.

Now, before reaching a certain nesting level, everything is fine. After two levels of nesting, Node gives up and prints[Object]As a placeholder:

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

{ name: ‘Flavio’, age: 35, person1: { name: ‘Tony’, age: 50, person2: { name: ‘Albert’, age: 21, person3: [Object] } } }

How to print the entire object?

The best way is to use it while preserving the beautiful print effect

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

where is it2Is the number of spaces used for indentation.

Another option is to use

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

But the problem is that now the nested objects after the second level are flattened, which may be a problem with complex objects.

Download mine for freeNode.js manual


More node tutorials: