Node: console.log(Error) appears to be cached

Created on 21 Jun 2017  路  3Comments  路  Source: nodejs/node

  • Version: v8.1.2
  • Platform: Darwin pro2015.local 16.6.0 Darwin Kernel Version 16.6.0: Fri Apr 14 16:21:16 PDT 2017; root:xnu-3789.60.24~6/RELEASE_X86_64 x86_64
  • Subsystem: Unknown


Run this code in Chrome 59 and in Node.js and you will notice there is a difference in output.

var e = new Error('first');
console.log(e);
e.message = 'new';
console.log(e);

It appears that node is caching the object so it looks the same at both console.log(e) when the message property actually changed.

Note this also happens on Node 7.9.0, Node 8.0.0, and Node 8.1.2 so it's unclear if this is a bug or expected behavior.

This question originated on StackOverflow.

V8 Engine question

Most helpful comment

This is expected because what you're seeing is the stack trace, which includes the error message once it's generated. The stack trace is generated lazily and only once (for performance reasons), so that is why you see the same output both times.

If you however change your code to output e.message, you will see the expected change in output.

All 3 comments

This is expected because what you're seeing is the stack trace, which includes the error message once it's generated. The stack trace is generated lazily and only once (for performance reasons), so that is why you see the same output both times.

If you however change your code to output e.message, you will see the expected change in output.

@mscdex Thanks! But why does Chrome has different behavior than Node?

It's just a difference in how non-string values are "inspected." Node internally uses util.inspect() in console.log(). I don't know offhand what logic Chrome uses, but it's obviously different.

Here is where util.inspect() specifically checks for an Error object. It then formats it by checking for a stack (which is a getter on Error instances and thus gets chosen in most cases) and falling back to a conversion of the object to a string.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dfahlander picture dfahlander  路  3Comments

seishun picture seishun  路  3Comments

sandeepks1 picture sandeepks1  路  3Comments

jmichae3 picture jmichae3  路  3Comments

addaleax picture addaleax  路  3Comments