Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do not log symbols using util.inspect

I have this object which has some symbols properties on it:

{
  foo: 'bar',
  [Symbol(raw.json.bytes)]: 13,
  [Symbol(raw.json.str)]: '{"foo":"bar"}'
} 

now, I added those symbol properties myself, so maybe I can change how I add them using Object.defineProperty. Is there some way to prevent logging the symbols either:

  1. using an option to util.inspect(v, opts)
  2. Or by using Object.defineProperty?

Either way I am using util.inspect() to stringify the object, and my preference is to pass it an option to not log non-enumerable properties or what not.


1 Answers

You can do it if the showHidden option is set to false (default) by using non-enumerable symbols.

To do this, define symbols the following way:

Object.defineProperty(obj, symbol, {
  enumerable: false,  //that matters!
  configurable: true, //or false
  writable: true,     //or false
  value: value
})

Properties defined like this (not necessarily symbols1) will not be included in util.inspect calls if the showHidden option is false.


1: Defining non-enumerable non-symbol properties has the side effect of skipping them when iterating over the keys/values of an object with for..in loops, Object.keys() or Object.values(). Read more on MDN or in this SO post

like image 164
FZs Avatar answered Dec 31 '25 09:12

FZs