Buffer.from(str[, encoding])
Node.js FS子產品方法速查
- str {String} 需要編碼的字元串
- encoding {String} 編碼時用到,預設:'utf8'
建立一個新的 Buffer 包含給定的 JavaScript 字元串 str。如果提供 encoding 參數,将辨別字元串的字元編碼。如果沒有提供 encoding 參數,預設為 'utf8'。
```
const buf1 = Buffer.from('this is a tést');
console.log(buf1.toString());
// prints: this is a tést
console.log(buf1.toString('ascii'));
// prints: this is a tC)st
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
console.log(buf2.toString());
如果 str 不是一個有效的 String 則抛出一個 TypeError 錯誤。