代码之家  ›  专栏  ›  技术社区  ›  Dimitrios Desyllas

每字节读取一个nodejs缓冲区字节

  •  -1
  • Dimitrios Desyllas  · 技术社区  · 7 年前

    假设我有以下缓冲区:

    const buf1 = Buffer.from('12ADFF1345', 'hex');
    

    1 回复  |  直到 7 年前
        1
  •  0
  •   Dimitrios Desyllas    7 年前

    您可以使用以下方法:

    const readBufferBytes = (buffer, callback, index=0) => {
      if(!Buffer.isBuffer(buffer)) return callback(new Error('Invalid value for buffer has been provided'));
      if (typeof callback !== 'function') return callback(new Error('The callback is not a function'));
      try {
        callback(null, buffer.readUInt8(index));
        // We iterate the buffer as an array that each array posision is a byte length.
        return readBufferBytes(buffer,callback,index+1);
      } catch(e) {
         return callback(e);
      }
    }
    

    const readBufferBytes = (buffer, callback, index=0) => {
      if(!Buffer.isBuffer(buffer)) return callback(new Error('Invalid value for buffer has been provided'));
      if (typeof callback !== 'function') return callback(new Error('The callback is not a function'));
    
      try {
        return process.nextTick(()=>{
            callback(null, buffer.readUInt8(index));
            readBufferBytes(buffer,callback,index+1);
        });
      } catch(e) {
         return process.nextTick(()=>{callback(e);});
      }
    
    }
    

    关于这些函数必须注意的一点是,我将缓冲区作为数组进行迭代,每个位置包含1个字节。因此,索引传入 readUInt8 0 并且在每次迭代中增加1。

    推荐文章