0

This looks similar to console.log inconsistent with JSON.stringify, but: I'd like to know what exactly happens behind the screen, because I can't understand what exactly happens here, and why JSON.stringify() does not show the error text. Here's my code (saved in firstio.js)

var fs = require('fs')

try {
  var file = fs.readFileSync(process.argv[2])
}
catch(error) {
  console.log(error.toString());
  console.log(JSON.stringify(error, null, 2));
  process.exit()
}
console.log(file.toString().split("\n").length - 1)

when run as follows: node firstio.js the output is as follows:

TypeError: path must be a string
{}

If JSON.stringify is converting the error object where is the error text that toString() apparently can find?

When it is run as follows: node firstio.js nonexistingfile the output is:

Error: ENOENT, no such file or directory 'nonexistingfile'
{
  "errno": -2,
  "code": "ENOENT",
  "path": "nonexistingfile",
  "syscall": "open"
}
5
  • Because it's two entirely different functions? Commented Mar 2, 2016 at 13:06
  • 1
    stringify process enumarable properties. Maybe error does not have any. Commented Mar 2, 2016 at 13:08
  • stackoverflow.com/questions/18391212/… Commented Mar 2, 2016 at 13:10
  • Ok, while searching for a PHP-like var_dump() for Javascript, the top answers here on SO mentioned JSON.stringify(), but - as I found and wondered about - that does not work for the error variable. Turns out that is the answer: the error variable is not an enumerable object. Thanks @Radek Pech. I'll mark your answer. Which still leaves the question does JS have a var_dump() equivalent. No it does not, though console.dir() seems to come close. Commented Mar 2, 2016 at 13:42
  • Radek, if you create an answer I'll mark it as accepted. Commented Mar 2, 2016 at 13:49

1 Answer 1

1

Method JSON.stringify() process objects based on their enumarable properties.

But window.Error object does not have any enumerable properties thus JSON.stringify(error) returns only empty object.

You can write an error directly into console:

console.log(new Error('Something happened'));

Which will output Error: Something happened.

Or you can write your own method to stringify error; see Is it not possible to stringify an Error using JSON.stringify?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.