You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ws模块开发WebSocket服务时收到的数据为何是Buffer而非字符串

问题原因

ws 模块的 message 事件默认返回原始二进制 Buffer 类型数据,不会自动转换为字符串。你打印输出的 <Buffer 74 65 73 74> 正好对应字符串 test 的十六进制 ASCII 编码,数据本身没有传输错误,只是类型不符合你的预期。

解决方案

有两种常用方式可以获取字符串类型的接收数据:

  • 直接对收到的 Buffer 调用 toString() 方法手动转换,该方法兼容性最高,适配所有 ws 版本:
const wss = new WebSocket.Server({ server });

wss.on("connection", function (ws) {
    ws.on("message", function (asdfasdf) {
        const receiveStr = asdfasdf.toString()
        console.log("got new id from client", receiveStr);
    });
});
  • 初始化 WebSocket 服务时添加 encoding: 'utf8' 配置项,模块会自动将接收到的消息转为 UTF-8 编码的字符串:
const wss = new WebSocket.Server({ 
  server,
  encoding: 'utf8'
});

wss.on("connection", function (ws) {
    ws.on("message", function (receiveStr) {
        console.log("got new id from client", receiveStr);
    });
});

内容的提问来源于stack exchange,提问作者stackers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 12:45:04