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

时间:2019-01-01 13:24:53

标签: node.js

假设我有以下缓冲区:

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

我如何读取其中包含的所有字节以进行处理?

1 个答案:

答案 0 :(得分:0)

您可以使用以下方法:

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。