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

在 Node.js v6.0.0 之前, Buffer 实例是通过 Buffer 构造函数创建的,它根据参数返回不同的 Buffer

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

因为 new Buffer() 会根据参数的类型而不同,所以如果没有正确地校验传给 new Buffer() 的参数、就可能引起安全性与可靠性问题。

为了使 Buffer 实例的创建更可靠, new Buffer() 构造函数已被废弃,建议使用 Buffer.from()Buffer.alloc()、和 Buffer.allocUnsafe()

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.