Only reading N bytes from a 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 a specific piece of data? For instance:

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

Where N is the number of bytes I expect. Thus, the callback receives only N of M bytes.

Solution (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); } }); 
+6
source share
2 answers

Readable streams in node v0.10 + have read() , which allows you to request the number of bytes.

+3
source

You can create a buffer in which your data will only store the amount that your buffer stores.

 var buf = Buffer(someNum) 

Here's the documentation for details http://nodejs.org/api/buffer.html#buffer_new_buffer_size

0
source

Source: https://habr.com/ru/post/979778/


All Articles