node.js - 如何将 Node 缓冲区转换为字符串,如 console.log show

标签 node.js

我想将缓冲区记录为字符串,但我不想使用 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/

相关文章:

node.js - 如何在node.js中获得对regexp-match-indices的支持?

node.js - Node 中第一次调用函数的时间

javascript - Node.js 将页面 View 转移到其他页面 View 堆栈

javascript - 是否可以通过机器人删除所有以前的消息?

Node.js 的 PHP 包函数替代方案

javascript - 检查 Jest 中数组不包含虚假值

node.js - 在 ExpressJS 的 Post 或 Put 请求中仅接受 JSON 内容类型

node.js - 如何更新 github 上的 npm 包

node.js - 在 Basic Http Auth Express.js 之后重定向

node.js - Express.js 动态路由