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

Node.js中console.log()输出WebSocket消息显示为<Buffer>而非文本的问题求助

Node.js中console.log()输出WebSocket消息显示为而非文本的问题求助

大家好,我遇到了一个奇怪的问题:不管我怎么处理,Node.js里用console.log()输出WebSocket消息的时候,总是显示成<Buffer>格式,但这个问题只在VS Code的PowerShell集成终端里出现,在浏览器里消息显示是正常的。

客户端代码(client.html)

<html>
<head>
<meta charset="UTF-8">
</head>
<script>
//calling the constructor which gives us the websocket object: ws
let ws = new WebSocket('ws://localhost:8000');
console.log(ws);

ws.onopen = (event) => ws.send("This is a message from client");
ws.onmessage = (message) => console.log(message.data.toString('utf8'))
</script>
<body>
<h1>This is a client page</h1>
</body>
</html>

服务端代码(server.js)

const http = require("http");
const websocket = require("ws");

//creating a http server
const server = http.createServer((req, res) => {
res.end("I am connected");
});

const wss = new websocket.Server({ server });

wss.on("connection", (ws, req) => {
setTimeout(() => {
ws.send("This is a message from server, connection is established");
}, 3000);

ws.on("message", (msg) => {
console.log(msg.toString('utf-8'));
});
});

//making it listen to port 8000
server.listen(8000);

我试过直接访问WebSocket消息的[data]属性,也试过用.toString('utf-8')转换,但都没成功。

我的Node.js版本是v18.13.0。

备注:内容来源于stack exchange,提问作者Shimi Shimson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 13:33:05