• Node.js Video Tutorials

Node.js - Buffer.allocUnsafeSlow() 方法



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

使用 buffer.allocUnsafeSlow() 建立的緩衝區,其分配的記憶體未初始化,內容未知,即可能包含舊緩衝區的內容。它也可能包含敏感資料。可以使用 Buffer.fill(0) 用 0 預填充緩衝區。

語法

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

Buffer.allocUnsafeSlow(size)

引數

此方法接受一個引數。解釋如下。

  • size − 這是一個整數值,表示要建立的緩衝區的長度。

返回值

Buffer.allocUnsafeSlow() 方法將返回一個指定大小的新緩衝區。

示例

此示例將使用 NodeJS Buffer.allocUnsafeSlow() 方法建立一個緩衝區:

const buf = Buffer.allocUnsafeSlow(5);
console.log(buf);

輸出

緩衝區大小為 5。執行上述程式,將生成以下輸出:

<Buffer 00 00 00 00 00>

示例

此示例將使用 Buffer.allocUnsafeSlow() 方法建立緩衝區,並使用 Buffer.fill() 方法填充緩衝區的值。

const buf = Buffer.allocUnsafeSlow(5);
buf.fill('a')
console.log(buf);

輸出

緩衝區大小為 5,我們已使用值 'a' 填充了緩衝區的內容。執行上述程式,將生成以下輸出:

<Buffer 61 61 61 61 61>

示例

在此示例中,我們將看到如果使用的大小不是數字將會丟擲什麼錯誤。

const buf = Buffer.allocUnsafeSlow('5');
buf.fill('a')
console.log(buf);

輸出

由於使用的大小是字串,這是一個無效的值,因為大小必須是整數值。執行上述程式時,將丟擲如下所示的錯誤。執行上述程式,將生成以下輸出:

TypeError [ERR_INVALID_ARG_TYPE]: The "size" argument must be of type number. Received type string
   at Function.allocUnsafeSlow (buffer.js:294:3)
   at Object.<anonymous> (C:\nodejsProject\src\testbuffer.js:1:20)
   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.