仅从node.js中的套接字读取前N个字节 [英] Read only first N bytes from socket in node.js
本文介绍了仅从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);
});
//...
};
有没有办法只读取定义的数据部分?例如:
Is there a way to read only defined portion of data? For example:
c.on('data', N, function(data) {
//Read first N bytes
});
其中N是我期望的字节数.因此,回调仅从M个字节中获取N个.
Where N is number of bytes I expect. So the callback gets only N out of M bytes.
解决方法是(感谢mscdex):
The solution is (thanks to mscdex):
c.on('readable', function() {
var chunk,
N = 4;
while (null !== (chunk = c.read(N))) {
console.log('got %d bytes of data', chunk.length);
}
});
推荐答案
Readable streams in node v0.10+ have a read()
that allows you to request a number of bytes.
这篇关于仅从node.js中的套接字读取前N个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文