静态方法:Buffer.from(object[, offsetOrEncoding[, length]])


【Static method: Buffer.from(object[, offsetOrEncoding[, length]])

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

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

import { Buffer } from 'node:buffer';

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>const { Buffer } = require('node:buffer');

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>

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

【For objects that support Symbol.toPrimitive, returns Buffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding).】

import { Buffer } from 'node:buffer';

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>const { Buffer } = require('node:buffer');

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>

如果 object 不具有所提到的方法,或者不是 Buffer.from() 变体所适用的其他类型,将会抛出 TypeError

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