How can I get the full object in Node.js's console.log(), rather than '[Object]'?

 

You need to use util.inspect():

const util = require('util')

console.log(util.inspect(myObject, {showHidden: false, depth: null, colors: true}))

// alternative shortcut
console.log(util.inspect(myObject, false, null, true /* enable colors */))

 

util.inspect() automatically pretty-prints object and array representations, but produces multiline output only when needed.

 

By default, when you use console.log() in Node.js to print an object, it may display [Object] as a placeholder instead of the actual object contents. To print the full object in the console, you can use the util.inspect() function from the built-in util module. Here's how you can do it:

 

const util = require('util');
const obj = { foo: 'bar', baz: { nested: true } };
console.log(util.inspect(obj, { showHidden: false, depth: null }));

 

In this example, we import the util module and define an object obj with some properties and nested objects.

To print the full object, we use util.inspect() and pass the object as the first argument. The second argument is an options object where you can customize the behavior of util.inspect().

  • showHidden (default: false): If set to true, it will show non-enumerable properties of the object.
  • depth (default: 2): Specifies the depth to which nested objects will be inspected. Setting it to null will print the full object.

By setting showHidden to false and depth to null, we ensure that all properties and nested objects of the object are printed in the console.

When you run the code, you should see the complete object representation in the console output, including its properties and nested objects.

Keep in mind that util.inspect() provides more advanced options and customization for inspecting objects in Node.js. You can refer to the Node.js documentation for util.inspect() for more details on additional options and usage.

 

 


Tags:

Share:

Related posts