Buffer.from(string[, encoding])


  • string <string> 要编码的字符串。
  • encoding <string> string 的字符编码。默认值: 'utf8'

创建一个包含 string 的新 Bufferencoding 参数指定 string 的字符编码。

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

console.log(buf1.toString());
// 打印: this is a tést
console.log(buf2.toString());
// 打印: this is a tést
console.log(buf1.toString('ascii'));
// 打印: this is a tC)st

如果 string 不是一个字符串,则抛出 TypeError

  • string <string> A string to encode.
  • encoding <string> The encoding of string. Default: 'utf8'.

Creates a new Buffer containing string. The encoding parameter identifies the character encoding of string.

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('ascii'));
// Prints: this is a tC)st

A TypeError will be thrown if string is not a string.