- How to log an object in Node.js [Practical Examples]
- Learn how to log an object in Node.js by understanding the available options
- Option-1: Using the console object
- Option-2: Using the util module
- Option-3: Using JSON
- Set up Lab Environment
- Example~1: How to log an object in Node.js using the util module
- Example~2: How to log an object in Node.js using JSON methods
- Method-1: console-logging JSON
- Method-2: JSON.stringify() method
- Conclusion
- 1 thought on “How to log an object in Node.js [Practical Examples]”
- Leave a Comment Cancel reply
- Node.js Tutorial
- console: log() method
- Syntax
- Parameters
- Return value
- Logging objects
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- 5 Ways to Log an Object to the Console in JavaScript
- Like all JavaScript developers, I love to use the console to inspect variables while I’m coding. Here are 5 methods to output an object’s keys and properties to the console window.
- Method 1 — Use console.log(object)
How to log an object in Node.js [Practical Examples]
where the inspect method takes the target object and reveals its contents depending on the supplied options.
console.log(' %j', ); // OR console.log(JSON.stringify(, , ));
where %j represents JSON in string format. Alternatively, you can control the output using the stringify() method.
This tutorial walks you through how to log an object in Node.js practically using the console.log() method with the util module or JSON. Lastly, you will find an alternative way to view an entire object tree without the console.log() method.
First, it would be best to understand the options we will use. Let’s get started.
Learn how to log an object in Node.js by understanding the available options
This section teaches you how the console.log() method, the util module, and JSON work. With that knowledge, you will find it comfortable to apply them.
Option-1: Using the console object
The console object is one of the high-level Node APIs for printing any data type. It has multiple methods like the log() method, mainly used during Node.js debugging.
console.log() extends to the process object, an interface for reading or writing to the operating system. For example, we can print the new Date() using the process object.
process.stdout.write(new Date().toString())
The process object expects a string input. That is why we convert the new Date() object to a string before writing to the OS.
The best part is that the high-level console.log() method does the lengthy work for you. So, you don’t have to convert most of the built-in objects to a string before printing them.
Otherwise, you must convert the object into a string before inspecting its contents.
You can customize console.log() to print a massive object, throwing its hugely nested branches. Better yet, you can effortlessly control the output using the higher-level console.dir() method.
Option-2: Using the util module
The util module presents you with multiple functions to print formatted strings. Most of the utility functions are significant for Node.js debugging.
For example, during debugging, the inspect() method lets you control an object’s content to your desired nesting level and appearance. It does that through many options like
- showHidden : a boolean property revealing (or not) an object’s enumerable properties. It defaults to false.
- depth : the number of nested levels you wish to recurse. It defaults to 2. You can recurse all branches by setting it to null .
- colorize : enables the pretty printing of the output.
Option-3: Using JSON
JSON, short for JavaScript Object Notation, is a data representation format mainly used to work with API and configuration data.
Its familiarity with data handling arises from its lightweight, easy-to-integrate, readable, and writable formats. Being a superset of JavaScript, you do not import any library to work with JSON in Node.js.
You can print JSON data by console-logging its string %j representation of an object. Or use the stringify() method to handle more readable data.
Now that you understand the needed tools, let me show you how to log an object in Node.js practically.
Set up Lab Environment
Create and open an entry file with a code editor. Next, build a deeply nested object tree.
const managers = < do : < teams : [ < re : < teams : [ < mi : < teams : [], roles : ['HR'] >>, < fa: < teams: [], roles: ['Sales'] >> ] >, >, < so : < teams: [], roles: ['Marketing'] >> ] >, la : < teams : [ < ti : < teams : [ < doo : < teams : [ < jane : < teams : [], roles : ['AI'] >, doe : < teams: [ < sam : < teams: [], roles: ['DS'] >> ] > > ], >, smith : < teams : [], roles : ['Web3'] >> ] > > ] > >
I have created the managers object with deeply nested subcategories (of teams and roles ) inside the index.js file. If you console-log the object,
you will get concealed objects.
Here is how to see the hidden branches.
Example~1: How to log an object in Node.js using the util module
Import the inspect() method from the util module.
const output = inspect(managers, < depth: null, colorize: true >)
We print a colorized output revealing every child of the managers object tree.
Now log the output on the console.
Finally, let’s run the file with the node command.
We get the expected output.
Example~2: How to log an object in Node.js using JSON methods
Method-1: console-logging JSON
The simplest way to decode an object is to console-log an unpretty JSON version.
console.log('managers: %j', managers)
You get a less organized object structure.
Here is how to log an organized object structure using the JSON.stringify() method.
Method-2: JSON.stringify() method
Feed the JSON.stringify() function with the managers object.
console.log(JSON.stringify(managers, null, 2))
null means we do not replace the object, and 2 is an indentation level (of two white spaces).
On rerunning the index.js file,
you get the following output:
Bonus tricks
Apart from console.log() , we can also get the desired tree view using the console.dir() method with a depth of any integer.
Better yet, we can set the depth value as Infinity to enable us to see all the object tree branches.
Conclusion
Knowing how to log an object in Node.js is straightforward if you understand the process and console objects, the util module, and JSON. Then, you can control the viewable tree depth, as shown in this tutorial.
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
1 thought on “How to log an object in Node.js [Practical Examples]”
There is also a NPM package that might help you, a drop-in no-fuss replacement for console.log called console-log-json https://www.npmjs.com/package/console-log-json). The nice thing about it is that it will create consistent JSON formatted logs, despite the fact that you can throw at console.log() any number of parameters in any order, including other JSON objects as well as Error objects and plain strings. It also handles automatically adding some extra helpful attributes such as time stamps and file where the console.log() was called from, etc.. These all get printed to STDOUT so any log shipping and aggregator can pick it up and parse the JSON. Reply
Leave a Comment Cancel reply
Node.js Tutorial
- Getting Started
- Getting started with Node.js
- Install Node.js on Ubuntu 20.04
- Setup Node.js with Visual Studio Code IDE
- Setup Node.js with Sublime Text IDE
- Setup Node.js with Atom IDE
- Setup Node.js with Eclipse IDE
- Node.js Read a JSON File
- Node.js Write to a File
- Node.js Parse CSV Data
- Node.js forEach() Loop
- Node,js async while Loop
- Node.js async for loop
- Node.js get all files in directory recursively
- Node.js loop through files in directory
console: log() method
The console.log() method outputs a message to the web console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects.
Note: This feature is available in Web Workers
Syntax
log(obj1) log(obj1, /* …, */ objN) log(msg) log(msg, subst1, /* …, */ substN)
Parameters
A list of JavaScript objects to output. Objects are output in the order listed. Please be warned that if you log objects in the latest versions of Chrome and Firefox, what you get logged on the console is a reference to the object, which is not necessarily the ‘value’ of the object at the moment in time you call console.log() , but it is the value of the object at the moment you open the console.
A JavaScript string containing zero or more substitution strings.
JavaScript objects with which to replace substitution strings within msg . This gives you additional control over the format of the output.
See Outputting text to the console in the documentation of console for details.
Return value
Logging objects
Information about an object is lazily retrieved. This means that the log message shows the content of an object at the time when it’s first viewed, not when it was logged. For example:
const obj = >; console.log(obj); obj.prop = 123;
This will output <> . However, if you expand the object’s details, you will see prop: 123 .
If you are going to mutate your object and you want to prevent the logged information from being updated, you can deep-clone the object before logging it. A common way is to JSON.stringify() and then JSON.parse() it:
.log(JSON.parse(JSON.stringify(obj)));
There are other alternatives that work in browsers, such as structuredClone() , which are more effective at cloning different types of objects.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 7, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.5 Ways to Log an Object to the Console in JavaScript
Like all JavaScript developers, I love to use the console to inspect variables while I’m coding. Here are 5 methods to output an object’s keys and properties to the console window.
If you are like me, you’ve run into the issue of trying to log a JavaScript object or array directly to the console — but what’s the best way?
There is the argument that we should just use the debugger statement and inspect variables and objects in the Dev Tools’ debugger window.
But personally, when figuring out an algorithm or trying a new code syntax, I like to prototype quickly in the console. (Sue me! 🙂)
Here are 5 ways to log JavaScript objects directly to the console window.
Method 1 — Use console.log(object)
W hen developing in a browser, the console.log() method called with an object or objects as arguments will display the object or objects.
“The Console method log() outputs a message to the web console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects.” — MDN Docs
Check out a code snippet using console.log(object) :
And here is the screenshot resulting from that code:
That object’s properties can be further inspected by clicking the arrow at left:
Of course, not all JavaScript is developed in or can be debugged in browsers — so developers may be using alert() instead of console.log() .
And alert(object) does not work the same way at all — it instead shows an alert that reads [object Object] :