Michael Tang
Michael Tang

Reputation: 4916

`console.log([])` and `console.log([].toString())` provide different outputs

I've noticed that, in NodeJS, console.log([]) and console.log([].toString()) produce [] and a blank string, respectively. I'm wondering why this is so and how I can get the output of console.log([]) as a string?

I understand for arrays, I can simply wrap the .toString() with brackets [], but for other constructed objects, say a Buffer:

var b = new Buffer('hi');

console.log(b); // <Buffer 68 69>
console.log(b.toString()); // hi
console.log('' + b); // hi

Is is possible to get the bare console.log(b) output as a string so I can perhaps concatenate it with another string?

Thanks.

Upvotes: 1

Views: 124

Answers (1)

Alexey Ten
Alexey Ten

Reputation: 14374

I guess you use node.js.

Read the documentation. console.log uses util.format.

So the answer is:

var util = require('util');
var b = new Buffer('hi');
var str = util.format(b);

Upvotes: 2

Related Questions