当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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]])。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。