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>

    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>

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