Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read only first N bytes from socket in 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);
  });
  //...
};

Is there a way to read only defined portion of data? For example:

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

Where N is number of bytes I expect. So the callback gets only N out of M bytes.

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);
  }
});
like image 939
Max Avatar asked Dec 17 '14 12:12

Max


1 Answers

Readable streams in node v0.10+ have a read() that allows you to request a number of bytes.

like image 184
mscdex Avatar answered Oct 15 '22 09:10

mscdex