處理多國語言字串時,「字元數」與「位元組數」往往並不相同。Buffer.byteLength 就是專門用來取得字串位元組長度的方法。
它會回傳一段字串在指定編碼下所佔用的位元組數。這點與 String.prototype.length 有本質差異——後者回傳的是字元數量,而非位元組數。
Buffer.byteLength(string, [encoding])
str = '\u00bd + \u00bc = \u00be'; console.log(str + ": " + str.length + " characters, " + Buffer.byteLength(str, 'utf8') + " bytes"); // ½ + ¼ = ¾: 9 characters, 12 bytes
這個例子很直觀:同樣一段字串,字元數是 9,但在 utf8 編碼下卻佔了 12 個位元組。這正是為什麼在計算 Buffer 所需空間時,必須用 byteLength 而非 length。
它會依不同編碼採用不同的計算策略,例如 hex 是長度除以二、utf16 是長度乘以二,而 utf8 等則交由底層的 internal.byteLength 精算:
Buffer.byteLength = function(str, enc) {
var ret;
str = str + '';
switch (enc) {
case 'ascii':
case 'binary':
case 'raw':
ret = str.length;
break;
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = str.length * 2;
break;
case 'hex':
ret = str.length >>> 1;
break;
default:
ret = internal.byteLength(str, enc);
}
return ret;
};