静态方法:Buffer.from(array)


🌐 Static method: Buffer.from(array)

  • array 整数数组[]
  • 返回:<Buffer>

使用范围为 0255 的字节数组分配一个新的 Buffer。数组中超出该范围的条目将被截断以适应该范围。

🌐 Allocates a new Buffer using an array of bytes in the range 0255. Array entries outside that range will be truncated to fit into it.

import { Buffer } from 'node:buffer';

// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);const { Buffer } = require('node:buffer');

// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);

如果 array 是一个类似 Array 的对象(即具有 number 类型的 length 属性),它会被当作数组处理,除非它是 BufferUint8Array。这意味着所有其他 TypedArray 变体都被当作 Array 处理。要从支持 TypedArray 的字节创建 Buffer,请使用 Buffer.copyBytesFrom()

🌐 If array is an Array-like object (that is, one with a length property of type number), it is treated as if it is an array, unless it is a Buffer or a Uint8Array. This means all other TypedArray variants get treated as an Array. To create a Buffer from the bytes backing a TypedArray, use Buffer.copyBytesFrom().

如果 array 不是 Array 或其他适用于 Buffer.from() 的类型,将会抛出 TypeError

🌐 A TypeError will be thrown if array is not an Array or another type appropriate for Buffer.from() variants.

Buffer.from(array)Buffer.from(string) 也可能像 Buffer.allocUnsafe() 一样使用内部 Buffer 池。