最近项目有个需求需要在和第三方API接口进行交互时,在JSON字符串最前面加上16个字节的签名字节,为了简化问题忽略JSON以及16个字节的具体取值。
错误代码:
buff = Buffer.from('abcd012', 'utf8');
arr = [];
crypted = new Buffer(16) + buff;
console.log(typeof crypted);
console.log(crypted);
console.log(crypted.length);
arr.push(crypted);
console.log(Buffer.concat(arr)); //报错
输出:
string
abcd012
23
buffer.js:446
throw new TypeError(kConcatErrMsg);
^
TypeError: "list" argument must be an Array of Buffer or Uint8Array instances
at Function.Buffer.concat (buffer.js:446:13)
at Object.<anonymous> (/home/pengpengzhou/test/uint8arraytest2.js:9:20)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Function.Module.runMain (module.js:694:10)
at startup (bootstrap_node.js:204:16)
at bootstrap_node.js:625:3
从输出可以看出来,Buffer.concat报错了,因为arr虽然是list,但是它的数组元素不是Uint8Array类型。根本原因是两个Buffer相加等到的是一个字符串,而不再是Buffer。Buffer是建立在Uint8Array类型上的,所有Buffer的实例也都是Uint8Array的实例,所以正确的写法有:
方法一:只使用Buffer
buff = Buffer.from('abcd012', 'utf8');
arr = [];
crypted = Buffer.concat([new Buffer(16), buff]); //只改这这一句
console.log(typeof crypted);
console.log(crypted);
console.log(crypted.length);
arr.push(crypted);
console.log(Buffer.concat(arr));
输出:
object
<Buffer 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 61 62 63 64 30 31 32>
23
<Buffer 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 61 62 63 64 30 31 32>
方法二:直接使用Uint8Array
buff = Buffer.from('abcd012', 'utf8');
arr = [];
crypted = new Uint8Array(buff.length + 16);
for (var i = 0; i < buff.length; i++) {
crypted[i + 16] = buff[i];
}
console.log(typeof crypted);
console.log(crypted);
console.log(crypted.length);
arr.push(crypted);
console.log(Buffer.concat(arr));
输出:
object
Uint8Array [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 97, 98, 99, 100, 48, 49, 50 ]
23
<Buffer 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 61 62 63 64 30 31 32>
Uint8Array是内置变量不用引用包。这是这类Buffer问题的通用解决办法,类似的错误还有:
- Argument must be a Buffer or Uint8Array
- Arguments must be Buffers or Uint8Arrays
- "list" argument must be an Array of Buffer or Uint8Array instances
相关文章: