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


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

新增于: v8.2.0

对于 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.

AltStyle によって変換されたページ (->オリジナル) /