How Can I Get the Full Object in Node.Js’s Console.Log(), Rather than ‘[Object]’?

When working with JavaScript in Node.js, you might have encountered a situation where you want to log an object to the console using console.log(). However, by default, the console.log() method only displays the string ‘[Object]’ instead of the actual contents of the object. This can be frustrating when you need to debug or inspect the object’s properties and values.

Fortunately, there are a few ways to get the full object in Node.js’s console.log(). Let’s explore them:

1. Using JSON.stringify()

One way to display the full object in the console is by using the JSON.stringify() method. This method converts a JavaScript object into a JSON string, allowing you to log the entire object as a string.

const obj = { name: 'John', age: 30, city: 'New York' };
console.log(JSON.stringify(obj));

The output will be:

{"name":"John","age":30,"city":"New York"}

2. Using util.inspect()

Another approach is to use the util.inspect() method from the Node.js ‘util’ module. This method returns a string representation of an object, including its properties and values.

const util = require('util');
const obj = { name: 'John', age: 30, city: 'New York' };
console.log(util.inspect(obj));

The output will be:

{ name: 'John', age: 30, city: 'New York' }

3. Using console.dir()

The console.dir() method can also be used to display the full object in the console. This method is similar to console.log(), but it provides a more detailed output for objects.

const obj = { name: 'John', age: 30, city: 'New York' };
console.dir(obj);

The output will be:

{ name: 'John', age: 30, city: 'New York' }

These are three different ways to get the full object in Node.js’s console.log(). Choose the method that best suits your needs and start debugging and inspecting your objects more effectively.

Remember to remove or comment out the console.log() statements once you’re done debugging, as they can clutter your code and affect performance in production environments.


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *