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

I am wondering how Node.js prints objects via console.log (object).

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

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 this code using >node constructor.js prints an empty object. However, Chrome prints what I 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 attributes (e.g. console.log(person.car) ) in Node and not the object itself (e.g. console.log(person) )

Why is this? Do you use Chrome and Node separate prototypes for the console object, although they have the same javascript mechanism?

+5
source share
1 answer

console.log() in node uses util.inspect() , which uses Object.keys() for objects that return only its own enumerated properties . Also, by default , Object.defineProperty() sets enumerable: false unless you explicitly set it to true .

+3
source

Source: https://habr.com/ru/post/1232926/


All Articles