静态方法:Buffer.from(string[, encoding])
【Static method: Buffer.from(string[, encoding])】
创建一个包含 string 的新 Buffer。encoding 参数用于指定将 string 转换为字节时使用的字符编码。
【Creates a new Buffer containing string. The encoding parameter identifies
the character encoding to be used when converting string into bytes.】
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。
【A TypeError will be thrown if string is not a string or another type
appropriate for Buffer.from() variants.】
Buffer.from(string) 也可能像 Buffer.allocUnsafe() 那样使用内部 Buffer 池。