當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Node.js Buffer.from(arrayBuffer[, byteOffset[, length]])用法及代碼示例


靜態方法:Buffer.from(arrayBuffer[, byteOffset[, length]])

添加於:v5.10.0

參數

這將創建 ArrayBuffer 的視圖,而無需複製底層內存。例如,當傳遞對 TypedArray 實例的 .buffer 屬性的引用時,新創建的 Buffer 將與 TypedArray 的底層 ArrayBuffer 共享相同的分配內存。

import { Buffer } from 'node:buffer';

const arr = new Uint16Array(2);

arr[0] = 5000;
arr[1] = 4000;

// Shares memory with `arr`.
const buf = Buffer.from(arr.buffer);

console.log(buf);
// Prints: <Buffer 88 13 a0 0f>

// Changing the original Uint16Array changes the Buffer also.
arr[1] = 6000;

console.log(buf);
// Prints: <Buffer 88 13 70 17>const { Buffer } = require('node:buffer');

const arr = new Uint16Array(2);

arr[0] = 5000;
arr[1] = 4000;

// Shares memory with `arr`.
const buf = Buffer.from(arr.buffer);

console.log(buf);
// Prints: <Buffer 88 13 a0 0f>

// Changing the original Uint16Array changes the Buffer also.
arr[1] = 6000;

console.log(buf);
// Prints: <Buffer 88 13 70 17>

可選的 byteOffsetlength 參數指定 arrayBuffer 中將由 Buffer 共享的內存範圍。

import { Buffer } from 'node:buffer';

const ab = new ArrayBuffer(10);
const buf = Buffer.from(ab, 0, 2);

console.log(buf.length);
// Prints: 2const { Buffer } = require('node:buffer');

const ab = new ArrayBuffer(10);
const buf = Buffer.from(ab, 0, 2);

console.log(buf.length);
// Prints: 2

如果 arrayBuffer 不是 ArrayBuffer SharedArrayBuffer 或適用於 Buffer.from() 變體的其他類型,則會拋出 TypeError

請務必記住,支持ArrayBuffer 可以覆蓋超出TypedArray 視圖邊界的內存範圍。使用 TypedArraybuffer 屬性創建的新 Buffer 可能會超出 TypedArray 的範圍:

import { Buffer } from 'node:buffer';

const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
console.log(arrA.buffer === arrB.buffer); // true

const buf = Buffer.from(arrB.buffer);
console.log(buf);
// Prints: <Buffer 63 64 65 66>const { Buffer } = require('node:buffer');

const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
console.log(arrA.buffer === arrB.buffer); // true

const buf = Buffer.from(arrB.buffer);
console.log(buf);
// Prints: <Buffer 63 64 65 66>

相關用法


注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 Buffer.from(arrayBuffer[, byteOffset[, length]])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。