`

node.js Buffer

阅读更多

在js中基础类型没有二进制byte类型,但是js提供了ArrayBuffer群来处理各种二进制的存储,而node.js也为我们封装了一个用于存储二进制的通用Buffer类,这里说说Buffer。

 

1.Buffer构造:

function Buffer(subject, encoding, offset) {
  if (!(this instanceof Buffer)) {
    return new Buffer(subject, encoding, offset);
  }

  var type;

  // Are we slicing?
  if (typeof offset === 'number') {
    if (!Buffer.isBuffer(subject)) {
      throw new TypeError('First argument must be a Buffer when slicing');
    }

    this.length = +encoding > 0 ? Math.ceil(encoding) : 0;
    this.parent = subject.parent ? subject.parent : subject;
    this.offset = offset;
  } else {
    // Find the length
    switch (type = typeof subject) {
      case 'number':
        this.length = +subject > 0 ? Math.ceil(subject) : 0;
        break;

      case 'string':
        this.length = Buffer.byteLength(subject, encoding);
        break;

      case 'object': // Assume object is array-ish
        this.length = +subject.length > 0 ? Math.ceil(subject.length) : 0;
        break;

      default:
        throw new TypeError('First argument needs to be a number, ' +
                            'array or string.');
    }

    // Buffer.poolSize 这里的poolSize默认大小是8KB
    if (this.length > Buffer.poolSize) {
      // Big buffer, just alloc one.   大于8kb的buffer将重新分配内存
      this.parent = new SlowBuffer(this.length); // SlowBuffer才是真正存储的地方,这里的长度为buffer的真实长度,大于8KB
      this.offset = 0;

    } else if (this.length > 0) {
      // Small buffer. 当new的buffer小于8KB的时候,就会把多个buffer放到同一个allocPool 的SlowBuffer里面
      if (!pool || pool.length - pool.used < this.length) allocPool(); // 当前已有的allocPool大小不够,如是重新分配一个allocPool,新分配的allocPool成为当前活动的allocPool
      this.parent = pool; 
      this.offset = pool.used;
      // Align on 8 byte boundary to avoid alignment issues on ARM.
      pool.used = (pool.used + this.length + 7) & ~7; // 将pool原本使用的大小变成8的倍数,例如你实际用了9byte,它会说你用了16byte,这样你就浪费了7byte,目的是提供性能。

    } else {
      // Zero-length buffer 如果当前pool够放,就直接放进去
      this.parent = zeroBuffer;
      this.offset = 0;
    }

    // 下面这部分是写操作
    // optimize by branching logic for new allocations
    if (typeof subject !== 'number') {
      if (type === 'string') {
        // We are a string
        this.length = this.write(subject, 0, encoding);
      // if subject is buffer then use built-in copy method
      } else if (Buffer.isBuffer(subject)) {
        if (subject.parent)
          subject.parent.copy(this.parent,
                              this.offset,
                              subject.offset,
                              this.length + subject.offset);
        else
          subject.copy(this.parent, this.offset, 0, this.length);
      } else if (isArrayIsh(subject)) {
        for (var i = 0; i < this.length; i++)
          this.parent[i + this.offset] = subject[i];
      }
    }
  }

  SlowBuffer.makeFastBuffer(this.parent, this, this.offset, this.length);
}

我们创建一个buffer的时候,本质上内容是存放在SlowBuffer里面的,由于node.js对小于8KB的buffer做了pool处理,你可以理解为buffer池。正是这个原因出现了几种情况:

1.buffer大于8KB:这种情况下buffer直接使用一个SlowBuffer存放数据,不使用pool存储。

2.buffer小于8KB:小于的时候会检测当前pool够不够放,不够放就重新分配一个pool,然后新分配的pool就成了当前pool。这个时候之前的那个pool里面空出来的内存就直接浪费掉了。

3.如果当前pool足够容纳buffer,就直接放到当前pool里面,一个pool里面可以存放多个buffer。

针对2和3这种pool的情况,如果buffer的长度不是8的倍数,将会自动补齐。这样也会浪费掉一些空间。

Buffer.poolSize = 8 * 1024;
var pool; // 看到没,allocPool的时候新的会把旧的pool直接替换掉,这样旧的pool里面没用到的内存就浪费了。其实这种浪费并不可怕,可怕的是buffer的不正常释放导致整个pool内存无法被gc回收形成真正的内存泄露。

function allocPool() {
  pool = new SlowBuffer(Buffer.poolSize);
  pool.used = 0;
}

 8KB事件:网传的8KB事件其实可以算做是一个buffer的错误用法,直接将buffer的引用置为null,最后用gc进行清理内存。由于pool里面有几个空余的内存无法释放,导致整个pool都无法被回收。这也说明,我们在使用buffer的时候最好手动清空buffer。

 

2.写入操作:

function Buffer(subject, encoding, offset) :利用构造方法,构造的时候直接传入内容,这个内容可以是多种对象,string,数组,objet等。

concat(list, [totalLength]):这个方法是把list里面的buffer合并到一起。

Buffer.concat = function(list, length) {
  if (!Array.isArray(list)) {
    throw new TypeError('Usage: Buffer.concat(list, [length])');
  }

  if (list.length === 0) { // 当list长度为0时,返回一个长度为0的buffer
    return new Buffer(0);
  } else if (list.length === 1) { // 当list长度为1时,返回list[0];,其实就是自己
    return list[0];
  }

  if (typeof length !== 'number') { // 如果length没有值,就会计算list里面所有buffer的总长度
    length = 0;
    for (var i = 0; i < list.length; i++) {
      var buf = list[i];
      length += buf.length;
    }
  }

  var buffer = new Buffer(length); // buffer的分配是固定的,不是可变长的
  var pos = 0;
  for (var i = 0; i < list.length; i++) { // 把所有的buffer组合到一起
    var buf = list[i];
    buf.copy(buffer, pos);
    pos += buf.length;
  }
  return buffer;
};

 

buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd]):

Buffer.prototype.copy = function(target, target_start, start, end) {
  // set undefined/NaN or out of bounds values equal to their default
  if (!(target_start >= 0)) target_start = 0;
  if (!(start >= 0)) start = 0;
  if (!(end < this.length)) end = this.length;

  // Copy 0 bytes; we're done
  if (end === start ||
      target.length === 0 ||
      this.length === 0 ||
      start > this.length)
    return 0;

  if (end < start)
    throw new RangeError('sourceEnd < sourceStart');

  if (target_start >= target.length)
    throw new RangeError('targetStart out of bounds');

  if (target.length - target_start < end - start) // 这里需要注意,如果长度不够源的拷贝就会被截取
    end = target.length - target_start + start;

  // 最蛋疼的是这句话,parent.copy是啥真没理解,我对js的继承很蛋疼啊,一直搞不懂。有人说这里用的是slowbuffer的copy方法,但是在代码里面没有看到它的copy方法
  return this.parent.copy(target.parent || target, 
                          target_start + (target.offset || 0),
                          start + this.offset,
                          end + this.offset);
};

target:拷贝到的目标位置,这里需要注意的是目标buffer内存的大小是需要比源大的,否则不会拷贝的。

target_start:目标的起始位置

start:源的起始位置

end:源的结束位置,不能超过length,超过就设置为length。

这里需要注意的是:1.如果根本不能执行拷贝,会报异常这个还好。2.能拷贝但是目标的存放位置不够,这个时候就会出现截取,这个肯定不是我们想看到的,也是需要注意的。

 

Buffer.prototype.write = function(string, offset, length, encoding):

Buffer.prototype.write = function(string, offset, length, encoding) {
  // Support both (string, offset, length, encoding)
  // and the legacy (string, encoding, offset, length)
  if (isFinite(offset)) {
    if (!isFinite(length)) {
      encoding = length;
      length = undefined;
    }
  } else {  // legacy
    var swap = encoding;
    encoding = offset;
    offset = length;
    length = swap;
  }

  offset = +offset || 0;
  var remaining = this.length - offset;
  if (!length) {
    length = remaining;
  } else {
    length = +length;
    if (length > remaining) {
      length = remaining;
    }
  }
  encoding = String(encoding || 'utf8').toLowerCase(); // 这个是关键,这说明js的String对象写入到buffer的时候,默认字符编码为utf-8

  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.parent.hexWrite(string, this.offset + offset, length);
      break;

    case 'utf8':
    case 'utf-8':
      ret = this.parent.utf8Write(string, this.offset + offset, length);
      break;

    case 'ascii':
      ret = this.parent.asciiWrite(string, this.offset + offset, length);
      break;

    case 'binary':
      ret = this.parent.binaryWrite(string, this.offset + offset, length);
      break;

    case 'base64':
      // Warning: maxLength not taken into account in base64Write
      ret = this.parent.base64Write(string, this.offset + offset, length);
      break;

    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      ret = this.parent.ucs2Write(string, this.offset + offset, length);
      break;

    default:
      throw new TypeError('Unknown encoding: ' + encoding);
  }

  Buffer._charsWritten = SlowBuffer._charsWritten;

  return ret;
};

// 实现很简单,调用了底层的写入方法
Buffer.prototype.utf8Write = function(string, offset) {
  return this.write(string, offset, 'utf8');
};

Buffer.prototype.binaryWrite = function(string, offset) {
  return this.write(string, offset, 'binary');
};

Buffer.prototype.asciiWrite = function(string, offset) {
  return this.write(string, offset, 'ascii');
};

 

buf.fill(value, [offset], [end]):填充,填充的内容是value的内容,如果value是字符串的话,填充的是value = value.charCodeAt(0);值。

 

3.读取操作:

SlowBuffer.prototype.toString = function(encoding, start, end):大同小异这里只是贴出来,最喜的是默认为utf-8格式,因为我客户端传过来的数据就是utf-8,这样就不用转换了。

SlowBuffer.prototype.toString = function(encoding, start, end) {
  encoding = String(encoding || 'utf8').toLowerCase();
  start = +start || 0;
  if (typeof end !== 'number') end = this.length;

  // Fastpath empty strings
  if (+end == start) {
    return '';
  }

  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:
      throw new TypeError('Unknown encoding: ' + encoding);
  }
};

Buffer.prototype.utf8Slice = function(start, end) {
  return this.toString('utf8', start, end);
};

Buffer.prototype.binarySlice = function(start, end) {
  return this.toString('binary', start, end);
};

Buffer.prototype.asciiSlice = function(start, end) {
  return this.toString('ascii', start, end);
};

Buffer.prototype.utf8Write = function(string, offset) {
  return this.write(string, offset, 'utf8');
};

Buffer.prototype.binaryWrite = function(string, offset) {
  return this.write(string, offset, 'binary');
};

Buffer.prototype.asciiWrite = function(string, offset) {
  return this.write(string, offset, 'ascii');
};

 

Buffer.prototype.toJSON:把buffer直接转换成json对象输出

Buffer.prototype.toJSON = function() {
  return Array.prototype.slice.call(this, 0);
};

 Buffer.prototype.slice = function(start, end) :这个方法感觉跟拷贝差不多,但是算是各有利弊吧。它在操作的同时不会损害原有的buffer里面的内容。

 

Buffer.prototype.get = function get(offset) {
  if (offset < 0 || offset >= this.length)
    throw new RangeError('offset is out of bounds');
  return this.parent[this.offset + offset];
};


Buffer.prototype.set = function set(offset, v) {
  if (offset < 0 || offset >= this.length)
    throw new RangeError('offset is out of bounds');
  return this.parent[this.offset + offset] = v;
};

 这两个方法也是读写方法,而且还比较简洁,如果对buffer对象自身进行操作可以用这个。

分享到:
评论

相关推荐

    Node.js-Node.js0.12buffer.equals()ponyfill

    Node.js 0.12 buffer.equals() ponyfill

    Node.js-buf-compare-Node.js0.12Buffer.compare()ponyfill

    buf-compare - Node.js 0.12 Buffer.compare() ponyfill

    Node.js-Node.js`buffer.includes()`ponyfill

    Node.js `buffer.includes()` ponyfill

    深浅node.js.rar

    学习node.js 前端 深入浅出 Node.js (一):...深入浅出 Node.js (六): Buffer 那些事儿 深入浅出 Node.js (七): Connect 模块解析(之一) 深入浅出 Node.js (八): Connect 模块解析(之二)静态文件中间件

    Node.js 实战

    Node.js是一个非常具有极客精神的技术社区(我更想强调它本身代表的是一个社区,相比之前的一些大语言分支 c/c++/java什么的,那些大语言在针对某一些应用都有很固定的范式去遵循,javascript/node.js还是一个比较...

    string-buffer:浏览器中要使用的Node.js Buffer的实现

    它提供了Node.js Buffer对象的所有方法,但是将其数据存储在字符串中,这意味着它具有足够的可移植性,可以在浏览器和服务器中使用。 用法 var StringBuffer = require('string-buffer'); 或者 [removed][removed...

    Node.js-Node.js4.0`buffer.indexOf()`ponyfill

    Node.js 4.0 `buffer.indexOf()` ponyfill

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

    主要介绍了node.js中的buffer.Buffer.isBuffer方法使用说明,本文介绍了buffer.Buffer.isBuffer的方法说明、语法、接收参数、使用实例和实现源码,需要的朋友可以参考下

    Node.js Buffer用法解读

    主要介绍了Node.js Buffer用法解读,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

    Node.js MongoDB AngularJSWeb开发中文版.part1

    注意: Node.js MongoDB AngularJSWeb开发((中文版))pdf 由于文件比较大,次分为三部分上传,下载好三部分之后,放在同一个文件夹下,进行解压即可,另外两部分地址为: part2:...

    Node.js Buffer模块功能及常用方法实例分析

    本文实例讲述了Node.js Buffer模块功能及常用方法。分享给大家供大家参考,具体如下: Buffer模块 alloc()方法 alloc(size,fill,encoding)可以分配一个大小为 size 字节的新建的 Buffer,size默认为0 var buf = ...

    buffer-includes:Node.js`buffer.includes()`ponyfill

    不推荐使用 只需使用 。 自Node.js 6起已可用。... -Node.js buffer.indexOf() ponyfill buffer.equals() ponyfill -Node.js Buffer.compare() ponyfill 执照 麻省理工学院:copyright: Sindre Sorhus

    Node.JS介紹

    例 如,在服务器环境中,处理二进制数据通常是必不可少的,但Javascript对此支持不足,因此,V8.Node增加了Buffer类,方便并且高效地 处理二进制数据。因此,Node不仅仅简单的使用了V8,还对其进行了优化,使其在各...

    buffer:node.js中的缓冲模块,用于浏览器

    不会修改任何浏览器原型或在window上放置任何内容全面的测试套件(包括来自node.js核心的所有缓冲区测试)安装要直接使用此模块(不使用browserify),请安装它: npm install buffer 该模块以前称为native-buffer-...

    Node.js-Learning:Node学习笔记。A learning notes about Node.js

    Node.js 学习笔记 不要忘记star一下 加油! 目录 Node.js离不开JS,所以要好好巩固JS,这一块多是巩固ES6的相关特性 Class Symbol 作用域篇 扩展运算符 Part2 Node.js模块 学习Node.js的原生模块,从根本理解Node.js...

    buf-compare:Node.js 0.12 Buffer.compare()ponyfill

    不推荐使用 只需使用 。 自Node.js 0.12开始提供。 buf比较 Node.js 安装 $ npm install --save buf-compare 用法 var bufCompare = require ... -Node.js buffer.indexOf() ponyfill 执照 麻省理工学院:copyright:

    node.js中Buffer缓冲器的原理与使用方法分析

    主要介绍了node.js中Buffer缓冲器的原理与使用方法,结合实例形式分析了node.js Buffer缓冲器的基本概念、原理、创建、使用方法及相关操作注意事项,需要的朋友可以参考下

    安全缓冲区:更安全的Node.js缓冲区API

    安全缓冲区更安全的Node.js缓冲区API 在所有版本的Node.js中使用新的Node.js缓冲区API( Buffer.from , Buffer.alloc , Buffer.allocUnsafe , Buffer.allocUnsafeSlow )。 在可用时使用内置实现。安装npm ...

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

    主要介绍了node.js中的buffer.Buffer.byteLength方法使用说明,本文介绍了buffer.Buffer.byteLength的方法说明、语法、接收参数、使用实例和实现源码,需要的朋友可以参考下

Global site tag (gtag.js) - Google Analytics