Buffer.from(object[, offsetOrEncoding[, length]])
object
<Object> 支持Symbol.toPrimitive
或valueOf()
的对象。offsetOrEncoding
<integer> | <string> 字节偏移量或编码。length
<integer> 长度。
对于 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
。
object
<Object> An object supportingSymbol.toPrimitive
orvalueOf()
.offsetOrEncoding
<integer> | <string> A byte-offset or encoding.length
<integer> A length.
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.