如何以hexstringforms显示nodejs raw Buffer数据

以下代码使用SerialPort模块来侦听来自蓝牙连接的数据。

我期待在控制台中看到hex格式的数据stream。 但控制台只显示一些奇怪的符号。 我想知道如何解码和显示控制台中的数据。

var serialPort = new SerialPort("/dev/tty.EV3-SerialPort", { parser: SP.parsers.raw }, false); // this is the openImmediately flag [default is true] serialPort.open(function () { console.log('open'); serialPort.on('data', function(data) { var buff = new Buffer(data, 'utf8'); //no sure about this console.log('data received: ' + buff.toString()); }); }); 

这段代码将把数据缓冲区显示为一个hexstring:

 buff.toString('hex'); 

最佳答案是最简单的方法。

另一种方法:

 data = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); Array.prototype.map.call(new Uint8Array(data), x => ('00' + x.toString(16)).slice(-2)).join('').match(/[a-fA-F0-9]{2}/g).reverse().join('');