Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js console.log(object) prints empty object

I'm curious about the way Node.js prints objects through console.log(object).

I have the following code (from Learning Javascript Design Patterns book) under a file constructor.js

var defineProp = function(obj, key, value){
    var config = {
        value: value, 
        writable: true,
        configurable: true
    };
    Object.defineProperty(obj, key, config ); 
}

var person = Object.create(Object.prototype);


defineProp(person, "car", "Delorean"); 
defineProp(person, "dateOfBirth", "1981"); 
defineProp(person, "hasBeard", false); 

console.log(person); //This prints {} in Node.js

Running with that code with >node constructor.js prints an empty object. Chrome however, prints what I would expect if I run the code inside an HTML file.

console.log(person); //Chrome prints Object {car: "Delorean", dateOfBirth: "1981", hasBeard: false} 

Note: I can still print the attributes (such as console.log(person.car)) under Node, just not the object itself (such as console.log(person))

Why is this? Do Chrome and Node use separate prototypes for the console object, even though they share the same javascript engine?

like image 418
SamuelN Avatar asked Oct 05 '15 04:10

SamuelN


1 Answers

console.log() in node utilizes util.inspect(), which uses Object.keys() on objects, which returns only own enumerable properties. Also, by default, Object.defineProperty() sets enumerable: false if you do not explicitly set it to true.

like image 94
mscdex Avatar answered Oct 19 '22 23:10

mscdex