Reputation: 12882
i have decoded a base64-encoded string using buffers, now i have noticed something funny:
this works fine, outputs the decoded string as utf8
decoded = new Buffer(data.content, 'base64')
console.log('Decoded:' + decoded);
// outputs content of a markdown file
however, this outputs hex characters:
decoded = new Buffer(data.content, 'base64')
console.log(decoded);
// outputs<Buffer 23 20 33 30 32 34 20 66 ...>
why is this or what am i doing wrong? shouldn't the output be the same?
Upvotes: 2
Views: 280
Reputation: 13293
The argument of console.log
is formatted internally in node.js using util.format
. (See line 52 of https://github.com/joyent/node/blob/v0.11.4/lib/console.js)
When you call console.log(obj);
, obj
is passed directly to util.format
internally. When you call console.log('Decoded: '+obj)
, the string concatenation forces .toString()
to be called on obj
first, and then passes the resulting combined string to util.format
internally.
So, in the first case, node.js is formatting a String
object, in the second case, it's formatting a Buffer
object directly.
Upvotes: 2
Reputation: 3885
From the Mozilla Javascript Docs:
Every object has a toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected.
Node.js buffer docs: Buffer#toString.
Upvotes: -1