DIV CSS 佈局教程網

Node.js 中 buffer.toString 方法詳解與使用教學
編輯:關於JavaScript     

方法說明

把 Buffer 物件依指定編碼轉成字串,也可以只轉換其中一段範圍。

語法

buffer.toString([encoding], [start], [end])

參數說明

encoding:轉換後的字元編碼,預設為 'utf8'。

start:開始轉換的位置,預設為 0。

end:結束轉換的位置,預設為 buffer 的長度。

範例

var b = new Buffer(50);

console.log(b);

var c = b.toString('base64', 0, 10);

console.log(c);

原始碼

實作上會先對 start/end 做範圍夾限,再依編碼分派到對應的 slice 方法;若第一次比對失敗,會把編碼名稱轉小寫再試一次。

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;
    }
  }
};
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved