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