2

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?

2 Answers 2

2

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.

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

Comments

-1

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.

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.