Hahnemann
Hahnemann

Reputation: 4688

Why is node.js breaking incoming data into chunks?

The following code in node.js does not log all incoming data inside the brackets, rather, it breaks the data into chunks. So for example, if the incoming data is ABCDEF...XYZ it logs the data as [ABC][DEF]...[XYZ] rather than [ABCDEF...XYZ]. The data is much larger of course, the alphabet is just an example.

How should I write this so that all incoming data is logged once inside the brackets and not in parts?

chatServer.on('connection', function(client) 
{
    client.on('data', function(data) 
    {
        console.log('[' + data.toString() + ']');
    })    
})

Upvotes: 2

Views: 7122

Answers (2)

vossad01
vossad01

Reputation: 11958

Like matthewdavidson said, you are subscribing to every "chunk" of data that is sent rather than the whole message. It is more likely you want to capture the data in a closure within the function and still respond asynchronously. Try the following:

chatServer.on('connection', function(client) 
{
    var buffer = '';

    client.on('data', function(data) 
    {
        buffer += data;
    })

    client.on('end', function(){
        console.log('[' + buffer + ']');
    })
});

Checkout http://www.nodebeginner.org/#handling-post-requests for more information

Upvotes: 4

matchdav
matchdav

Reputation: 715

Well your data is arriving in packets, so (in this case) you should be concatenating the packets into a variable that you define outside the function.

buffer = '';

chatServer.on('connection', function(client) 
{
    client.on('data', function(data) 
    {
        buffer += data.toString();
    })    
});

console.log('[' + buffer + ']');

Upvotes: 8

Related Questions