Console.log-ing objects

Console logging object’s is straightforward in Node.js. A basic console.log(object) works well in printing out member variables and functions of an object:

var obj = {
    "name": "ditesh",
    "age": 13
};
console.log(obj); // Outputs { name: 'ditesh', age: 13 }

It’s quite easy to override the default behaviour, by attaching an inspect() method to the object:

obj.inspect = function() {
    return "my name is obj";
}
console.log(obj); // Outputs "my name is obj"

For those of us who deal with hex’es (eg, manipulating the buffer object), hexy.js is particularly useful. A sample from the documentation:

var hexy = require('hexy'),
b = new Buffer("\000\001\003\005\037\012\011bcdefghijklmnopqrstuvwxyz0123456789")
console.log(hexy.hexy(b))

would result in:

0000000: 00 01 03 05 1f 0a 09 62   63 64 65 66 67 68 69 6a  .......b cdefghij 
0000010: 6b 6c 6d 6e 6f 70 71 72   73 74 75 76 77 78 79 7a  klmnopqr stuvwxyz 
0000020: 30 31 32 33 34 35 36 37   38 39                    01234567 89

Neat!

This entry was posted in Code, Node.js, Technology. Bookmark the permalink.

One Response to Console.log-ing objects

  1. tuanpembual says:

    thanks,
    its really help me. :) )

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>