原创

Node.js 中 buffer.toString 函数的使用方式分析

Node.js 是一个基于Chrome JavaScript运行时建立的平台, 用于方便地搭建响应速度快、易于扩展的网络应用。Node.js 使用事件驱动, 非阻塞I/O 模型而得以轻量和高效,非常适合在分布式设备上运行的数据密集型的实时应用。

Node.js 是一个Javascript运行环境(runtime)。实际上它是对Google V8引擎进行了封装。V8引 擎执行Javascript的速度非常快,性能非常好。Node对一些特殊用例进行了优化,提供了替代的API,使得V8在非浏览器环境下运行得更好。

node.js 将buffer 对象转换成指定的字符编码,具体语法如下:

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

传递参数,具体如下:

encoding       转换成字符串后的字符编码,默认为 'utf8'
startbuffer 转换的起始位置,默认为 0
end buffer 转换的结束位置,默认为buffer长度

node.js源码,具体代码如下:

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

下面为大家分享一种简单的案例,具体代码如下:

var a = new Buffer(50);
console.log(a);
var b = a.toString('www.yoodb.com',0,10);
console.log(b);
~阅读全文-人机检测~

微信公众号“Java精选”(w_z90110),专注Java技术干货分享!让你从此路人变大神!回复关键词领取资料:如Mysql、Hadoop、Dubbo、Spring Boot等,免费领取视频教程、资料文档和项目源码。微信搜索小程序“Java精选面试题”,内涵3000+道Java面试题!

涵盖:互联网那些事、算法与数据结构、SpringMVC、Spring boot、Spring Cloud、ElasticSearch、Linux、Mysql、Oracle等

评论

分享:

支付宝

微信