Nodejs: Buffer報錯argument must be an Array of Buffer or Uint8Array instances

最近項目有個需求需要在和第三方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

相關文章:

《Nodejs 字符串string轉字節數組byte[]》

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章