我想将缓冲区记录为字符串,但我不想使用 buffer.toString() 方法
console.log(new Buffer(12))
显示
< Buffer 00 22 33 11 55 ...>
但是console.log('buffer:' + new Buffer(12))
显示
buffer: something can't read
我要
buffer: < Buffer 00 22 33 11 55 ...>
最佳答案
做
var b = new Buffer([0x41, 0x42, 0x43, 0x44]);
console.log(b);
// <Buffer 41 42 43 44>
和做一样
console.log(b.inspect());
鉴于
var b = new Buffer([0x41, 0x42, 0x43, 0x44]);
console.log('str' + b);
// strABCD
和做一样
console.log('str' + b.toString());
因为使用 +
进行字符串连接会使用 .toString()
自动将运算符的两边转换为字符串。另一方面,console.log(...)
在可能的情况下通过调用 .inspect()
将其参数转换为字符串。
做你想做的事情的最简单方法是让 console.log 通过传递多个参数来做它的事情
console.log('buffer:', new Buffer(12))
请注意,,
而不是 +
,因此不是使用 .toString
连接,而是让 console.log
将其每个参数单独字符串化。
关于node.js - 如何将 Node 缓冲区转换为字符串,如 console.log show,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21179524/