Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Why is node.js breaking incoming data into chunks?

Why is node.js breaking incoming data into chunks?

Problem

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() + ']');
    })    
})
Problem courtesy of: Hahnemann

Solution

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 + ']');
Solution courtesy of: matchdav

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Why is node.js breaking incoming data into chunks?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×