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


对于 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]('string'), offsetOrEncoding)

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 没有提到的方法或不是适合 Buffer.from() 变体的另一种类型,则将抛出 TypeError

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]('string'), offsetOrEncoding).

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>

A TypeError will be thrown if object does not have the mentioned methods or is not of another type appropriate for Buffer.from() variants.