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


Node.js Buffer.from(string[, encoding])用法及代碼示例

靜態方法:Buffer.from(string[, encoding])

添加於:v5.10.0

參數
  • string <string> 要編碼的字符串。
  • encoding <string> string 的編碼。 默認: 'utf8'

創建一個包含 string 的新 Bufferencoding 參數標識將string 轉換為字節時要使用的字符編碼。

import { Buffer } from 'node:buffer';

const buf1 = Buffer.from('this is a tést');
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');

console.log(buf1.toString());
// Prints: this is a tést
console.log(buf2.toString());
// Prints: this is a tést
console.log(buf1.toString('latin1'));
// Prints: this is a téstconst { Buffer } = require('node:buffer');

const buf1 = Buffer.from('this is a tést');
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');

console.log(buf1.toString());
// Prints: this is a tést
console.log(buf2.toString());
// Prints: this is a tést
console.log(buf1.toString('latin1'));
// Prints: this is a tést

如果 string 不是字符串或適合 Buffer.from() 變體的其他類型,則會拋出 TypeError

相關用法


注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 Buffer.from(string[, encoding])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。