Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 错误:无效的十六进制字符串_Node.js - Fatal编程技术网

Node.js 错误:无效的十六进制字符串

Node.js 错误:无效的十六进制字符串,node.js,Node.js,这是我的节点js代码 if (protocol == '01') { console.log('...goint to get Ack Obj...'); var o = getAckObj(hexString); console.log('...ack obj received...'); var msg = ackMsg(o); console.log('..going to write buffer...'); socket.write(new Buffer(msg

这是我的节点js代码

if (protocol == '01') {
  console.log('...goint to get Ack Obj...');
  var o = getAckObj(hexString);
  console.log('...ack obj received...');
  var msg = ackMsg(o);
  console.log('..going to write buffer...');
  socket.write(new Buffer(msg, 'hex')); //, 'binary');
  console.log('Server sent welcome: ' + msg);
}

.....

function ackMsg(dataObj) {
  var ackText = '';
  dataObj.len = '05'; //for ack msg its always 05
  var e = crc16(dataObj.len + dataObj.protocol + dataObj.serial, 'hex');
  dataObj.error = e.toString(16);
  return dataObj.start + dataObj.len + dataObj.protocol + dataObj.serial + dataObj.error + dataObj.stop;
}
以下是hexString
78780d010387113120864842000ccbe40d0a

在控制台上输出

...goint to get Ack Obj...
...ack obj received...
..going to write buffer...
buffer.js:348
      ret = this.parent.hexWrite(string, this.offset + offset, length);

你确定你的绳子的长度是均匀的吗?当您提供的十六进制字符串是奇数(
len%2!=0
)而不是所需的偶数时,缓冲区会引发该(不清楚的)错误消息

一个好的测试是记录您拥有的十六进制字符串,然后在Python中尝试:

>>> '8'.decode('hex')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/encodings/hex_codec.py", line 42, in hex_decode
    output = binascii.a2b_hex(input)
TypeError: Odd-length string
>>'8'。解码('hex')
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“/usr/lib/python2.7/encodings/hex_codec.py”,第42行,十六进制解码
输出=binascii.a2b_十六进制(输入)
TypeError:奇数长度字符串

我在GitHub上打开了一个pull请求,以修复更清晰的错误消息:

我在使用旧io.js时也遇到了这个问题,节点版本是1.2

下面是一个代码示例,我在其中遇到了如下错误:

const resultBuffer = new Buffer.concat(chunks.items);
fs.writeFileSync(resultFilePath, resultBuffer, {encoding: 'hex'});
我检查了两次
chunks.items
,然后使用了@JJ Geewax提到的简单十六进制oddless值,发现我的例子中的问题是节点fs模块和缓冲区之间的交互

为了让它工作,我改变了将原始缓冲区传递到具有正确编码的字符串的方式:

...
fs.writeFileSync(resultFilePath, resultBuffer.toString('hex'), {encoding: 'hex'});

可能有人觉得这很有用。

newbuffer()
将消息的编码作为第二个参数。通过编码,它指的是字符编码(默认为
utf8
),而不是数字编码。@ThalisK
hex
是与
Buffer
一起使用的有效编码(
base64
是另一种编码)@coure2011假设
dataObj.len
05
,并且您显示的值不包含该值,您确定
msg
正确吗?是的,正确。。。这个len并没有显示整个消息的长度,但它的用途有所不同。@coure2011和
msg。length
是一个偶数,对吗?