方法說明:
將buffer對象轉換成指定的字符編碼的字符串。
語法:
代碼如下:
buffer.toString([encoding], [start], [end])
接收參數:
encoding 轉換成字符串後的字符編碼,默認為 ‘utf8′
start buffer 轉換的起始位置,默認為 0
end buffer 轉換的結束位置,默認為buffer長度
例子:
代碼如下:
var b = new Buffer(50);
console.log(b);
var c = b.toString('base64',0,10);
console.log(c);
源碼:
代碼如下:
// toString(encoding, start=0, end=buffer.length)
Buffer.prototype.toString = function(encoding, start, end) {
var loweredCase = false;
start = start >>> 0;
end = util.isUndefined(end) ? this.length : end >>> 0;
if (!encoding) encoding = 'utf8';
if (start < 0) start = 0;
if (end > this.length) end = this.length;
if (end <= start) return '';
while (true) {
switch (encoding) {
case 'hex':
return this.hexSlice(start, end);
case 'utf8':
case 'utf-8':
return this.utf8Slice(start, end);
case 'ascii':
return this.asciiSlice(start, end);
case 'binary':
return this.binarySlice(start, end);
case 'base64':
return this.base64Slice(start, end);
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return this.ucs2Slice(start, end);
default:
if (loweredCase)
throw new TypeError('Unknown encoding: ' + encoding);
encoding = (encoding + '').toLowerCase();
loweredCase = true;
}
}
};