简体   繁体   English

Node.js [网络库]:如何使缓冲区对象成为字符串?

[英]Node.js [net library]: How to make the buffer object a string?

I am fairly new to Node.js, and I am creating a TCP client that sends and receives data from a certain server. 我对Node.js相当陌生,并且正在创建一个TCP客户端,该客户端从某个服务器发送和接收数据。

My problem is with the "data" event emitted when data is received through the socket. 我的问题是通过套接字接收数据时发出的"data"事件。

client.on('data', function(data) {    

    console.log('[TCP] Client received: ' + data); // Logs the message as it is supposed to be.

    console.log(data.split(" ")); // Does not work because it says that data is not a string
});

I tried toString(data) but it did not output it as it was logged by the console. 我尝试了toString(data)但是由于控制台记录了它,所以它没有输出。

So my question is: How can I convert this object to a string as it is logged in the console? 所以我的问题是:在控制台中记录该对象时,如何将其转换为字符串?

Thank you for your input :) 谢谢您的意见 :)

if data is a Buffer instance as it looks like, it's 如果data看起来像是一个Buffer实例,它就是

client.on('data', function(data) {
  console.log(data.toString('utf8'));
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM