DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> node.js中的buffer.write方法教程使用說明詳解
node.js中的buffer.write方法教程使用說明詳解
編輯:關於JavaScript     

方法說明:

將string使用指定的encoding寫入到buffer的offset處。

返回寫入了多少個八進制字節。

如果Buffer沒有足夠的空間來適應整個string,那麼將只有string的部分被寫入。

語法:

代碼如下:
buffer.write(string, [offset], [length], [encoding])

接收參數:

string                  String,被寫入buffer的數據.
offet                   number,可選,默認0.數據寫入到buffer的位置.
length                Number,可選,默認:buffer.length – offset,要寫入數據的長度
encoding           String,需要使用的編碼格式,可選,默認為”utf8″.

例子:

代碼如下:
buf = new Buffer(256);
 
len = buf.write('\u00bd + \u00bc = \u00be', 0);
 
console.log(len + " bytes: " + buf.toString('utf8', 0, len));

源碼:

代碼如下:
Buffer.prototype.write = function(string, offset, length, encoding) {
  // allow write(string, encoding)
  if (util.isString(offset) && util.isUndefined(length)) {
    encoding = offset;
    offset = 0;
  // allow write(string, offset[, length], encoding)
  } else if (isFinite(offset)) {
    offset = ~~offset;
    if (isFinite(length)) {
      length = ~~length;
    } else {
      encoding = length;
      length = undefined;
    }
  // XXX legacy write(string, encoding, offset, length) - remove in v0.13
  } else {
    if (!writeWarned) {
      if (process.throwDeprecation)
        throw new Error(writeMsg);
      else if (process.traceDeprecation)
        console.trace(writeMsg);
      else
        console.error(writeMsg);
      writeWarned = true;
    }
    var swap = encoding;
    encoding = offset;
    offset = ~~length;
    length = swap;
  }
  var remaining = this.length - offset;
  if (util.isUndefined(length) || length > remaining)
    length = remaining;
  encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
  if (string.length > 0 && (length < 0 || offset < 0))
    throw new RangeError('attempt to write beyond buffer bounds');
  var ret;
  switch (encoding) {
    case 'hex':
      ret = this.hexWrite(string, offset, length);
      break;
    case 'utf8':
    case 'utf-8':
      ret = this.utf8Write(string, offset, length);
      break;
    case 'ascii':
      ret = this.asciiWrite(string, offset, length);
      break;
    case 'binary':
      ret = this.binaryWrite(string, offset, length);
      break;
    case 'base64':
      // Warning: maxLength not taken into account in base64Write
      ret = this.base64Write(string, offset, length);
      break;
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      ret = this.ucs2Write(string, offset, length);
      break;
    default:
      throw new TypeError('Unknown encoding: ' + encoding);
  }
  return ret;
};

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved