• Node.js Video Tutorials

Node.js - Buffer.alloc() 方法



NodeJS 的 Buffer.alloc() 方法用於建立一個指定大小的新緩衝區。如果指定的大小大於 `buffer.constants.MAX_LENGTH` 或小於 0,則會丟擲型別為 ERR_INVALID_ARG_VALUE 的錯誤。如果指定的大小不是數字,則會丟擲 TypeError。

使用 Buffer.alloc() 建立緩衝區比其替代方法 Buffer.allocUnsafe() 慢,但它確保新建立的緩衝區不包含來自先前緩衝區的任何敏感資料以及先前為緩衝區建立分配的資料。

語法

以下是 NodeJS Buffer.alloc() 方法 的語法:

Buffer.alloc(size[, fill[, encoding]])

引數

此方法接受三個引數,如下所述。

  • size − (必填) 整數值,表示要建立的緩衝區的長度。

  • fill − (可選) 緩衝區填充的值。預設為 0。

  • encoding − (可選) 使用的編碼,預設為 utf8。如果使用字串,則需要指定編碼。

返回值

Buffer.alloc() 方法將返回指定大小的緩衝區。

示例

此示例演示如何使用 NodeJS Buffer.alloc() 方法建立緩衝區:

const mybuffer = Buffer.alloc(5);
console.log(mybuffer);

輸出

緩衝區大小為 5。由於未使用 fill 引數,因此預設值 0 填充了大小為 5 的緩衝區。

<Buffer 00 00 00 00 00>

示例

此示例演示如何使用 Buffer.alloc() 方法和 fill 引數建立緩衝區:

const mybuffer = Buffer.alloc(5, 5);
console.log(mybuffer);

輸出

緩衝區大小為 5。由於使用了 fill 引數值為 5。

<Buffer 05 05 05 05 05>

示例

此示例演示如何使用 Buffer.alloc() 方法並將 fill 引數設定為字串值:

const mybuffer = Buffer.alloc(5, 'a');
console.log(mybuffer);
console.log(mybuffer.toString());

輸出

緩衝區大小為 5。由於使用了 fill 引數值為字串 'a'。

<Buffer 61 61 61 61 61>
aaaaa

示例

此示例演示如果使用非數字大小引數會丟擲錯誤。

const mybuffer = Buffer.alloc('1');
console.log(mybuffer);
console.log(mybuffer.toString());

輸出

由於 size 引數為字串,這是一個無效的值,因為 size 必須是整數。執行上述程式時,將丟擲如下所示的錯誤。

TypeError [ERR_INVALID_ARG_TYPE]: The "size" argument must be of type number. Received type string
   at Function.alloc (buffer.js:271:3)
   at Object.<anonymous> (C:\nodejsProject\src\testbuffer.js:1:25)
   at Module._compile (internal/modules/cjs/loader.js:816:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
   at Module.load (internal/modules/cjs/loader.js:685:32)
   at Function.Module._load (internal/modules/cjs/loader.js:620:12)
   at Function.Module.runMain (internal/modules/cjs/loader.js:877:12)
   at internal/main/run_main_module.js:21:11
nodejs_buffer_module.htm
廣告
© . All rights reserved.