當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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]])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。