只能从node.js中的套接字读取前N个字节
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是我期望的字节数。 所以callback只有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); } });
节点v0.10 +中的可读stream具有read()
,允许您请求多个字节。
您可以创build一个缓冲区,其中的数据只能保存缓冲区的数量。
var buf = Buffer(someNum)
以下是有关详细信息的文档http://nodejs.org/api/buffer.html#buffer_new_buffer_size