• Node.js Video Tutorials

Node.js - Buffer.writeIntLE() 方法



NodeJS 的Buffer.writeIntLE()方法用於以小端序的形式將指定長度的位元組寫入緩衝區的指定偏移量。

語法

以下是Node.JS Buffer.writeIntLE() 方法的語法:

buf.writeIntLE(value, offset, bytelength)

引數

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

  • value − (必需) 要寫入緩衝區的數字。

  • offset − (必需) 指示寫入起始位置的偏移量。偏移量大於或等於 0,小於或等於 buffer.length-bytelength。預設值為 0

  • byteLength − (必需) 要寫入的位元組數。byteLength 必須在 0 到 6 之間。

返回值

buffer.writeIntLE() 方法寫入指定值並返回偏移量加上寫入的位元組數。

示例

為了建立一個緩衝區,我們將使用 NodeJS Buffer.alloc() 方法:

const buffer = Buffer.alloc(10);
buffer.writeIntLE(123, 0, 6);
console.log(buffer);

輸出

我們使用的偏移量為 0,位元組長度為 6。執行後,從第 0 位開始的值將被寫入建立的緩衝區。上面建立的緩衝區長度為 10。因此,我們只能使用 0 到 4 之間的偏移量值。任何大於 4 的值都會導致ERR_OUT_OF_RANGE錯誤。

<Buffer 7b 00 00 00 00 00 00 00 00 00>

示例

在這個例子中,我們將使用一個大於 6 的位元組長度。它應該丟擲如下所示的錯誤。

const buffer = Buffer.alloc(10);
buffer.writeIntLE(123, 0, 8);
console.log(buffer);

輸出

internal/buffer.js:83
   throw new ERR_OUT_OF_RANGE(type || 'offset',
   ^
   
RangeError [ERR_OUT_OF_RANGE]: The value of "byteLength" is out of range. It must be >= 1 and <= 6. Received 8
   at boundsError (internal/buffer.js:83:9)
   at Buffer.writeIntLE (internal/buffer.js:854:3)
   at Object.<anonymous> (C:\nodejsProject\src\testbuffer.js:2:8)
   at Module._compile (internal/modules/cjs/loader.js:1063:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
   at Module.load (internal/modules/cjs/loader.js:928:32)
   at Function.Module._load (internal/modules/cjs/loader.js:769:14)
   at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
   at internal/main/run_main_module.js:17:47 {
      code: 'ERR_OUT_OF_RANGE'
   }

示例

在這個例子中,我們將使用一個大於 buffer.length - bytelength 的偏移量。

const buffer = Buffer.alloc(10);
buffer.writeIntLE(123, 8, 3);
console.log(buffer);

輸出

偏移量必須在 0 到 7 之間。由於我們使用了 8,它將丟擲如下所示的錯誤:

internal/buffer.js:83
   throw new ERR_OUT_OF_RANGE(type || 'offset',
   ^
   
RangeError [ERR_OUT_OF_RANGE]: The value of "offset" is out of range. It must be >= 0 and <= 5. Received 6
   at boundsError (internal/buffer.js:83:9)
   at checkBounds (internal/buffer.js:52:5)
PS C:\nodejsProject> node src/testbuffer.js
internal/buffer.js:83
   throw new ERR_OUT_OF_RANGE(type || 'offset',
   ^
   
RangeError [ERR_OUT_OF_RANGE]: The value of "offset" is out of range. It must be >= 0 and <= 7. Received 8
   at boundsError (internal/buffer.js:83:9)
   at checkBounds (internal/buffer.js:52:5)
   at checkInt (internal/buffer.js:71:3)
   at writeU_Int24LE (internal/buffer.js:707:3)
   at Buffer.writeIntLE (internal/buffer.js:846:12)
   at Object.<anonymous> (C:\nodejsProject\src\testbuffer.js:2:8)
   at Module._compile (internal/modules/cjs/loader.js:1063:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
   at Module.load (internal/modules/cjs/loader.js:928:32)
   at Function.Module._load (internal/modules/cjs/loader.js:769:14) {
      code: 'ERR_OUT_OF_RANGE'
   }
nodejs_buffer_module.htm
廣告