Buffer.from()、Buffer.alloc() 与 Buffer.allocUnsafe()


在 6.0.0 之前的 Node.js 版本中, Buffer 实例是使用 Buffer 构造函数创建的,该函数根据提供的参数以不同方式分配返回的 Buffer

  • 将数字作为第一个参数传给 Buffer()(例如 new Buffer(10))会分配一个指定大小的新建的 Buffer 对象。 在 Node.js 8.0.0 之前,为此类 Buffer 实例分配的内存是未初始化的,并且可能包含敏感数据。 此类 Buffer 实例随后必须被初始化,可以使用 buf.fill(0) 或写满整个 Buffer。 虽然这种行为是为了提高性能,但开发经验表明,创建一个快速但未初始化的 Buffer 与创建一个速度更慢但更安全的 Buffer 之间需要有更明确的区分。 从 Node.js 8.0.0 开始, Buffer(num)new Buffer(num) 将返回已初始化内存的 Buffer
  • 传入字符串、数组、或 Buffer 作为第一个参数,则会将传入的对象的数据拷贝到 Buffer 中。
  • 传入 ArrayBufferSharedArrayBuffer,则返回一个与给定的数组 buffer 共享已分配内存的 Buffer

由于 new Buffer() 的行为因第一个参数的类型而异,因此当未执行参数验证或 Buffer 初始化时,可能会无意中将安全性和可靠性问题引入应用程序。

为了使 Buffer 实例的创建更可靠且更不容易出错,各种形式的 new Buffer() 构造函数都已被弃用,且改为单独的 Buffer.from()Buffer.alloc()Buffer.allocUnsafe() 方法。

开发者应将 new Buffer() 构造函数的所有现有用法迁移到这些新的 API。

如果 size 小于或等于 Buffer.poolSize 的一半,则 Buffer.allocUnsafe() 返回的 Buffer 实例可能是从共享的内部内存池中分配。 Buffer.allocUnsafeSlow() 返回的实例则从不使用共享的内部内存池。

In versions of Node.js prior to 6.0.0, Buffer instances were created using the Buffer constructor function, which allocates the returned Buffer differently based on what arguments are provided:

  • Passing a number as the first argument to Buffer() (e.g. new Buffer(10)) allocates a new Buffer object of the specified size. Prior to Node.js 8.0.0, the memory allocated for such Buffer instances is not initialized and can contain sensitive data. Such Buffer instances must be subsequently initialized by using either buf.fill(0) or by writing to the entire Buffer. While this behavior is intentional to improve performance, development experience has demonstrated that a more explicit distinction is required between creating a fast-but-uninitialized Buffer versus creating a slower-but-safer Buffer. Starting in Node.js 8.0.0, Buffer(num) and new Buffer(num) will return a Buffer with initialized memory.
  • Passing a string, array, or Buffer as the first argument copies the passed object's data into the Buffer.
  • Passing an ArrayBuffer or a SharedArrayBuffer returns a Buffer that shares allocated memory with the given array buffer.

Because the behavior of new Buffer() is different depending on the type of the first argument, security and reliability issues can be inadvertently introduced into applications when argument validation or Buffer initialization is not performed.

To make the creation of Buffer instances more reliable and less error-prone, the various forms of the new Buffer() constructor have been deprecated and replaced by separate Buffer.from(), Buffer.alloc(), and Buffer.allocUnsafe() methods.

Developers should migrate all existing uses of the new Buffer() constructors to one of these new APIs.

Buffer instances returned by Buffer.allocUnsafe() may be allocated off a shared internal memory pool if size is less than or equal to half Buffer.poolSize. Instances returned by Buffer.allocUnsafeSlow() never use the shared internal memory pool.