从node.js中的套接字中只读取前N个字节

Max*_*Max 6 javascript sockets buffer node.js

var server = net.createServer(function(c) {
  //...
  c.on('data', function(data) {
    //The data is all data, but what if I need only first N and do not need other data, yet.
    c.write(data);
  });
  //...
};
Run Code Online (Sandbox Code Playgroud)

有没有办法只读取已定义的数据部分?例如:

c.on('data', N, function(data) {
  //Read first N bytes
});
Run Code Online (Sandbox Code Playgroud)

其中N是我期望的字节数.所以回调只得到M个字节中的N个.

解决方案是(感谢mscdex):

c.on('readable', function() {
  var chunk,
      N = 4;
  while (null !== (chunk = c.read(N))) {
    console.log('got %d bytes of data', chunk.length);
  }
});
Run Code Online (Sandbox Code Playgroud)

msc*_*dex 7

节点 v0.10+ 中的可读流具有read()允许您请求多个字节的一个。