Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert node Buffer to string like console.log show

Tags:

node.js

I want log the buffer to string, but I am not want to use buffer.toString() method

console.log(new Buffer(12))

show

< Buffer 00 22 33 11 55 ...>

but console.log('buffer:' + new Buffer(12))

show

buffer: something can't read

I want

buffer: < Buffer 00 22 33 11 55 ...>

like image 303
guilin 桂林 Avatar asked Oct 21 '25 06:10

guilin 桂林


1 Answers

Doing

var b = new Buffer([0x41, 0x42, 0x43, 0x44]);
console.log(b);
// <Buffer 41 42 43 44>

is the same as doing

console.log(b.inspect());

whereas

var b = new Buffer([0x41, 0x42, 0x43, 0x44]);
console.log('str' + b);
// strABCD

is the same as doing

console.log('str' + b.toString());

because using string concatenation using + automatically converts both sides of the operator to strings using .toString(). console.log(...) on the other hand converts its arguments to strings by calling .inspect() when possible.

The easiest way to do what you want to do is to just let console.log do its thing by passing it multiple arguments

console.log('buffer:', new Buffer(12))

Note, the , instead of a +, so instead of concatenating using .toString, you let console.log stringify each of its arguments on its own.

like image 198
loganfsmyth Avatar answered Oct 22 '25 23:10

loganfsmyth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!