当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Node.js Buffer.from(object[, offsetOrEncoding[, length]])用法及代码示例


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

添加于:v8.2.0

参数

对于其 valueOf() 函数返回的值不严格等于 object 的对象,返回 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)

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

相关用法


注:本文由纯净天空筛选整理自nodejs.org大神的英文原创作品 Buffer.from(object[, offsetOrEncoding[, length]])。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。