Agnel Kurian
Agnel Kurian

Reputation: 59476

Writes and 'data' events in node.js sockets

When passing data over a node.js socket, who ensures that the data is received/read in its entirety? The caller or node.js?

Does each write correspond to a single 'data' event? Do I need to explicitly check to ensure the length of the data received corresponds to what was written? In other words, do I have to maintain a length header?

Upvotes: 0

Views: 165

Answers (1)

Alexandru
Alexandru

Reputation: 11

When you execute a write command: socket.write(data[, encoding][, callback]), the callback parameter will be executed when the data is finally written out - this may not be immediately.

A single write command might cause a sequence of data events:

const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
// chunk.length bytes of data received
});

The receiver needs to ensure that it receives the whole Buffer/String by checking the length of all received chunks. This will require having a length header or a similar marker.

P.S. The above answer holds for TCP like sockets.

Upvotes: 1

Related Questions