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

10
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);
  });
  //...
};

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

c.on('data', N, function(data) {
  //Read first N bytes
});

其中 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);
  }
});

谁给踩了?请评论! - Max
2个回答

7
在Node v0.10+中,可读流具有read()函数,允许您请求一定数量的字节。

0

我从回调函数中获取“data”缓冲区作为参数。创建另一个缓冲区如何帮助? - Max

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接