Reputation: 15872
Is it possible to print an objects contents e.g. methods and attributes in Node.js?
At the moment I'm trying to print the session object and get the following:
console.log("Session:" + session);
> Session:[object Object]
Maybe in a similar way to print_r(array) in PHP, or using .toString in Java.
Upvotes: 201
Views: 186996
Reputation: 12694
If you are still looking for some options, there is a NPM package that might help you, a drop-in replacement for console.log called 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.
Upvotes: 0
Reputation: 6614
console.dir with the depth argument set will do the trick. This will print JSON objects to any arbitrary depth. Depth:null means print every level.
console.dir(someObject, { depth: null })
Upvotes: 2
Reputation: 1
This will for most of the objects for outputting in nodejs console
var util = require('util')
function print (data){
console.log(util.inspect(data,true,12,true))
}
print({name : "Your name" ,age : "Your age"})
Upvotes: 0
Reputation: 3563
Try this one:
console.log("Session: %j", session);
If the object could be converted into JSON, that will work.
Upvotes: 306
Reputation: 4257
This will work with any object:
var util = require("util");
console.log(util.inspect(myObject, {showHidden: false, depth: null}));
Upvotes: 30
Reputation: 4561
function prettyJSON(obj) {
console.log(JSON.stringify(obj, null, 2));
}
// obj -> value to convert to a JSON string
// null -> (do nothing)
// 2 -> 2 spaces per indent level
Upvotes: 154
Reputation: 3224
To have an output more similar to the raw console.log(obj)
I usually do use console.log('Status: ' + util.inspect(obj))
(JSON is slightly different).
Upvotes: 33