Buffer.from(object[, offsetOrEncoding[, length]])


  • object <Object> 支持 Symbol.toPrimitivevalueOf() 的对象。
  • offsetOrEncoding <number> | <string> 字节偏移量或字符编码,取决于 object.valueOf()object[Symbol.toPrimitive]() 返回的值。
  • length <number> 长度,取决于 object.valueOf()object[Symbol.toPrimitive]() 的返回值。

对于 valueOf() 返回值不严格等于 object 的对象,返回 Buffer.from(object.valueOf(), offsetOrEncoding, length)

const buf = Buffer.from(new String('this is a test'));
// 打印: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>

对于支持 Symbol.toPrimitive 的对象,会返回 Buffer.from(object[Symbol.toPrimitive](), offsetOrEncoding, length)

class Foo {
  [Symbol.toPrimitive]() {
    return 'this is a test';
  }
}

const buf = Buffer.from(new Foo(), 'utf8');
// 打印: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>
  • object <Object> An object supporting Symbol.toPrimitive or valueOf()
  • offsetOrEncoding <number> | <string> A byte-offset or encoding, depending on the value returned either by object.valueOf() or object[Symbol.toPrimitive]().
  • length <number> A length, depending on the value returned either by object.valueOf() or object[Symbol.toPrimitive]().

For objects whose valueOf() function returns a value not strictly equal to object, returns Buffer.from(object.valueOf(), offsetOrEncoding, length).

const buf = Buffer.from(new String('this is a test'));
// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>

For objects that support Symbol.toPrimitive, returns Buffer.from(object[Symbol.toPrimitive](), offsetOrEncoding, length).

class Foo {
  [Symbol.toPrimitive]() {
    return 'this is a test';
  }
}

const buf = Buffer.from(new Foo(), 'utf8');
// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>