处理Node.js套接字数据
问题描述:
我有服务器从客户端[GPS设备]接收数据。我有问题以可读格式呈现数据(即从客户端获得的结果)。以下是我尝试的内容。
I have server receiving data from a client [GPS Device]. I have problem presenting the data (i.e the results obtained from the client) in a readable format. Below are the things I have tried.
执行:
console.log(data)
我得到
<Buffer d0 d7 3d 00 c4 56 7e 81>
还试过
console.log(data.toString())
但是我收到了不需要的结果:见下文:
But I get unwanted results:See below:
��A�V~�
这是我的完整代码:
var net = require('net');
var fs = require('fs');
var server = net.createServer(function (socket) {
console.log('Server started: Waiting for client connection ...');
console.log('Client connected:port,address: '+socket.remotePort, socket.remoteAddress);
socket.on('data', function (data) {
var date = new Date();
var today = date.getDate()+'_'+date.getMonth();
fs.appendFile(today+'_log.txt', data, function (err) {
if (err) throw err;
console.log(data.toString())
});
});
});
server.listen(my_port, my_ip);
感谢您的输入。
答
根据文档,您必须指定一个编码来获取String而不是Buffer:
According to the documentation, you must specify an encoding to get a String instead of a Buffer:
Event: 'data'#
Buffer object
Emitted when data is received. The argument data will be a Buffer or String. Encoding of data is set by socket.setEncoding().
您可以配置套接字以获取UTF-8中的数据,例如,使用:
You could configure the socket to get the data in UTF-8, for example, with:
socket.setEncoding('utf8');