Nono
Nono

Reputation: 13

Overriding the console in Node

So I would like to modify the console object on the interpreter (v9.4.0) :

>console = {foo : 1, bar : 5}
{foo : 1, bar : 5}

Such a hacker! Now let's verify :

>console
Console {
  log: [Function: bound consoleCall],
  debug: [Function: bound consoleCall],
  info: [Function: bound consoleCall],
  dirxml: [Function: bound consoleCall],
  warn: [Function: bound consoleCall],
  error: [Function: bound consoleCall],
  dir: [Function: bound consoleCall],
  time: [Function: bound consoleCall],
  timeEnd: [Function: bound consoleCall],
  trace: [Function: bound consoleCall],
  assert: [Function: bound consoleCall],
  clear: [Function: bound consoleCall],
  count: [Function: bound consoleCall],
  countReset: [Function: bound countReset],
  group: [Function: bound consoleCall],
  groupCollapsed: [Function: bound consoleCall],
  groupEnd: [Function: bound consoleCall],
  Console: [Function: Console],
  table: [Function: table],
  markTimeline: [Function: markTimeline],
  profile: [Function: profile],
  profileEnd: [Function: profileEnd],
  timeline: [Function: timeline],
  timelineEnd: [Function: timelineEnd],
  timeStamp: [Function: timeStamp],
  context: [Function: context],
  [Symbol(counts)]: Map {} }

Why the reaffection is not taken in consideration? And if it's somehow a "forbidden action..." why node is not telling me so?...

Thanks in advance

Upvotes: 1

Views: 524

Answers (1)

SirPeople
SirPeople

Reputation: 4348

I think that this is highly related with running your node within the CLI, whenever you execute a script that overrides the console, the console object will be overriden as expected. And I assume this is something to do in how they treat the Global Objects

Different environment of execution return different things and this is just because of how the context is wrapping your code:

  • Browser, it just works, you can try it out :D
  • Repl: https://repl.it/repls/VioletredAstonishingTelephone, basically they create the script and then run it.
  • CLI, your case, does not override it yet you can use Object.assign or modify the prototype to extend

So yes, the version matter because it affects the context in which your code gets executed (for node 12 it will work, for example)

http://www.joshuakehn.com/2011/10/20/Understanding-JavaScript-Context.html Here you can read a bit more about why context cannot be overwritten, and since console is just a sugar coating for this.console, you wont be able to overwrite it with a reassignment (there is no setter function).

For more into the global: https://nodejs.org/api/globals.html#globals_global

Upvotes: 1

Related Questions