广州明生医药有限公司


node.js中的buffer.toString方法使用说明

网络编程 node.js中的buffer.toString方法使用说明 06-22

方法说明:

将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;

    }

  }

};

node.js中的buffer.toJSON方法使用说明
方法说明:将buffer对象转换成json格式。语法:buffer.toJSON()接收参数:无例子:varbuf=newBuffer('test');varjson=JSON.stringify(buf);console.log(json);//'{"type":"Buffer","data"

node.js中的buffer.length方法使用说明
方法说明:该方法将返回buffer对象的长度。语法:buffer.length接收参数:无例子:buf=newBuffer(1234);console.log(buf.length);buf.write("somestring",0,"ascii");console.log(buf.

node.js中的buffer.fill方法使用说明
方法说明:将制定数据填充到buffer中。语法:buffer.fill(value,[offset],[end])接收参数:value将要填充的数据offet填充数据的开始位置,不指定默认为0end填充数


编辑:广州明生医药有限公司

标签:方法,语法,默认为,转换成,参数